import React, { useState } from 'react'
import { useAuth } from '../hooks/useAuth'
import type { AuthCredentials } from '../types'

interface SignInFormProps {
  onSuccess?: () => void
  onError?: (error: string) => void
  className?: string
}

export function SignInForm({ onSuccess, onError, className = '' }: SignInFormProps) {
  const { signIn, state } = useAuth()
  const [formData, setFormData] = useState<AuthCredentials>({
    email: '',
    password: '',
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    try {
      const result = await signIn(formData)
      
      if (result.error) {
        onError?.(result.error.message)
        return
      }
      
      onSuccess?.()
    } catch (error) {
      onError?.(error instanceof Error ? error.message : 'Sign in failed')
    }
  }

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target
    setFormData(prev => ({ ...prev, [name]: value }))
  }

  return (
    <form onSubmit={handleSubmit} className={`space-y-4 ${className}`}>
      <div>
        <label htmlFor="email" className="block text-sm font-medium text-gray-700">
          Email
        </label>
        <input
          id="email"
          name="email"
          type="email"
          value={formData.email}
          onChange={handleChange}
          required
          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
          placeholder="Enter your email"
        />
      </div>

      <div>
        <label htmlFor="password" className="block text-sm font-medium text-gray-700">
          Password
        </label>
        <input
          id="password"
          name="password"
          type="password"
          value={formData.password}
          onChange={handleChange}
          required
          className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
          placeholder="Enter your password"
        />
      </div>

      {state.error && (
        <div className="text-red-600 text-sm">
          {state.error.message}
        </div>
      )}

      <button
        type="submit"
        disabled={state.isLoading}
        className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50"
      >
        {state.isLoading ? 'Signing in...' : 'Sign In'}
      </button>
    </form>
  )
}