'use client'; import { useState } from 'react'; import { signIn } from 'next-auth/react'; import { useRouter, useSearchParams } from 'next/navigation'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { cn } from '@/lib/utils'; interface LoginFormProps { className?: string; } export function LoginForm({ className }: LoginFormProps) { const router = useRouter(); const searchParams = useSearchParams(); const callbackUrl = searchParams.get('callbackUrl') || '/dashboard'; const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [showPassword, setShowPassword] = useState(false); const [rememberMe, setRememberMe] = useState(false); const [isLoading, setIsLoading] = useState(false); const [error, setError] = useState(null); const [errors, setErrors] = useState<{ email?: string; password?: string }>({}); const validateForm = (): boolean => { const newErrors: { email?: string; password?: string } = {}; if (!email) { newErrors.email = 'Email is required'; } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) { newErrors.email = 'Enter a valid email address'; } if (!password) { newErrors.password = 'Password is required'; } else if (password.length < 6) { newErrors.password = 'Password must be at least 6 characters'; } setErrors(newErrors); return Object.keys(newErrors).length === 0; }; const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); setError(null); if (!validateForm()) { return; } setIsLoading(true); try { const result = await signIn('credentials', { email, password, redirect: false, }); if (result?.error) { setError('Invalid credentials. Please check your email and password.'); } else { router.push(callbackUrl); router.refresh(); } } catch (err) { setError('An error occurred while signing in. Please try again.'); } finally { setIsLoading(false); } }; return ( Sign In Enter your credentials to access the system
{error && (
{error}
)}
{ setEmail(e.target.value); if (errors.email) { setErrors((prev) => ({ ...prev, email: undefined })); } }} disabled={isLoading} className={cn(errors.email && 'border-red-500 focus-visible:ring-red-500')} /> {errors.email && (

{errors.email}

)}
{ setPassword(e.target.value); if (errors.password) { setErrors((prev) => ({ ...prev, password: undefined })); } }} disabled={isLoading} className={cn( 'pr-10', errors.password && 'border-red-500 focus-visible:ring-red-500' )} />
{errors.password && (

{errors.password}

)}
Forgot your password?
); } export default LoginForm;