'use client'; import { useState } from 'react'; import { useRouter } from 'next/navigation'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import { z } from 'zod'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '@/components/ui/form'; import { useToast } from '@/hooks/use-toast'; const loginSchema = z.object({ email: z.string().email('Please enter a valid email address'), password: z.string().min(6, 'Password must be at least 6 characters'), }); type LoginForm = z.infer; export function LoginForm() { const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const { toast } = useToast(); const form = useForm({ resolver: zodResolver(loginSchema), defaultValues: { email: '', password: '', }, }); const onSubmit = async (data: LoginForm) => { setIsLoading(true); try { const response = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); const result = await response.json(); if (!response.ok) { throw new Error(result.error || 'Login failed'); } toast({ title: 'Welcome back!', description: "You've been successfully logged in.", }); // Redirect based on user role if (result.user.role === 'admin') { router.push('/admin'); } else { router.push('/dashboard'); } // Refresh the page to update auth state router.refresh(); } catch (error) { toast({ title: 'Login failed', description: error instanceof Error ? error.message : 'An unexpected error occurred', variant: 'destructive', }); } finally { setIsLoading(false); } }; return ( Welcome back Enter your credentials to access your account
( Email )} /> ( Password )} />
); }