// File: app/(auth)/login/page.tsx 'use client'; import { useState } from 'react'; import { useForm } from 'react-hook-form'; import { zodResolver } from '@hookform/resolvers/zod'; import * as z from 'zod'; import { signIn } from 'next-auth/react'; import { useRouter } from 'next/navigation'; import { Eye, EyeOff, Loader2 } from 'lucide-react'; import { toast } from 'sonner'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; // กำหนด Schema สำหรับตรวจสอบข้อมูลฟอร์ม const loginSchema = z.object({ username: z.string().min(1, 'กรุณาระบุชื่อผู้ใช้งาน'), password: z.string().min(1, 'กรุณาระบุรหัสผ่าน'), }); type LoginValues = z.infer; export default function LoginPage() { const router = useRouter(); const [isLoading, setIsLoading] = useState(false); const [showPassword, setShowPassword] = useState(false); // Removed local errorMessage state in favor of toast // ตั้งค่า React Hook Form const { register, handleSubmit, formState: { errors }, } = useForm({ resolver: zodResolver(loginSchema), defaultValues: { username: '', password: '', }, }); // ฟังก์ชันเมื่อกด Submit async function onSubmit(data: LoginValues) { setIsLoading(true); try { // เรียกใช้ NextAuth signIn (Credential Provider) const result = await signIn('credentials', { username: data.username, password: data.password, redirect: false, // เราจะจัดการ Redirect เอง }); if (result?.error) { // กรณี Login ไม่สำเร็จ toast.error('เข้าสู่ระบบไม่สำเร็จ', { description: 'ชื่อผู้ใช้งานหรือรหัสผ่านไม่ถูกต้อง กรุณาลองใหม่', }); return; } // Login สำเร็จ -> ไปหน้า Dashboard toast.success('เข้าสู่ระบบสำเร็จ', { description: 'กำลังพาท่านไปยังหน้า Dashboard...', }); router.push('/dashboard'); router.refresh(); // Refresh เพื่อให้ Server Component รับรู้ Session ใหม่ } catch (_error) { toast.error('เกิดข้อผิดพลาด', { description: 'ระบบขัดข้อง กรุณาลองใหม่อีกครั้ง หรือติดต่อผู้ดูแลระบบ', }); } finally { setIsLoading(false); } } return ( LCBP3 DMS กรอกชื่อผู้ใช้งานและรหัสผ่านเพื่อเข้าสู่ระบบ
{/* Username Field */}
{errors.username &&

{errors.username.message}

}
{/* Password Field */}
{/* ปุ่ม Show/Hide Password */}
{errors.password &&

{errors.password.message}

}
); }