import React, { useEffect, useState } from 'react'; import { useForm, usePage } from '@inertiajs/react'; import { useTranslation } from 'react-i18next'; import toast from 'react-hot-toast'; import { LoaderCircle, Mail, Lock } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Checkbox } from '@/components/ui/checkbox'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import InputError from '@/components/input-error'; import TextLink from '@/components/text-link'; interface LoginFormProps { onSuccess?: (userData: any) => void; canResetPassword?: boolean; } export default function LoginForm({ onSuccess, canResetPassword = true }: LoginFormProps) { const [hasTriedSubmit, setHasTriedSubmit] = useState(false); const { t } = useTranslation('auth'); const { props } = usePage<{ errors: Record }>(); const { data, setData, post, processing, errors, clearErrors, reset } = useForm({ email: '', password: '', remember: false, }); useEffect(() => { if (hasTriedSubmit && Object.keys(errors).length > 0) { toast.error(Object.values(errors).join(' ')); } }, [errors, hasTriedSubmit]); const submit = (e: React.FormEvent) => { e.preventDefault(); setHasTriedSubmit(true); post('/login', { preserveScroll: true, onSuccess: () => { if (onSuccess) { onSuccess({ user: { email: data.email } }); // Pass basic user info; full user from props in parent } reset(); }, }); }; useEffect(() => { if (!hasTriedSubmit) { return; } const errorKeys = Object.keys(errors); if (errorKeys.length === 0) { return; } const field = document.querySelector(`[name="${errorKeys[0]}"]`); if (field) { field.scrollIntoView({ behavior: 'smooth', block: 'center' }); field.focus(); } }, [errors, hasTriedSubmit]); return (
{ setData('email', e.target.value); if (errors.email) { clearErrors('email'); } }} />
{canResetPassword && ( {t('login.forgot')} )}
{ setData('password', e.target.value); if (errors.password) { clearErrors('password'); } }} />
setData('remember', Boolean(checked))} />
{Object.keys(errors).length > 0 && (

{Object.values(errors).join(' ')}

)}
); }