import { useState } from 'react' import { signIn } from 'next-auth/react' import Link from 'next/link' interface LoginFormProps { callbackUrl?: string onSuccess?: () => void onError?: (error: string) => void } export function LoginForm({ callbackUrl = '/', onSuccess, onError }: LoginFormProps) { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [isLoading, setIsLoading] = useState(false) const [error, setError] = useState(null) const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() setIsLoading(true) setError(null) try { const result = await signIn('credentials', { email, password, redirect: false, }) if (result?.error) { const errorMessage = getErrorMessage(result.error) setError(errorMessage) onError?.(errorMessage) } else if (result?.ok) { onSuccess?.() if (callbackUrl) { window.location.href = callbackUrl } } } catch (err) { const errorMessage = 'An unexpected error occurred' setError(errorMessage) onError?.(errorMessage) } finally { setIsLoading(false) } } return (
{error && (
{error}
)}
setEmail(e.target.value)} className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm" placeholder="Email address" />
setPassword(e.target.value)} className="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-green-500 focus:border-green-500 focus:z-10 sm:text-sm" placeholder="Password" />
Forgot password?
) } function getErrorMessage(error: string): string { const errorMessages: Record = { CredentialsSignin: 'Invalid email or password', default: 'An error occurred during sign in', } return errorMessages[error] ?? errorMessages.default } export default LoginForm