import { FormEvent, useEffect, useState } from 'react';
import { Head, useForm } from '@inertiajs/react';
import { useTranslation } from 'react-i18next';
import InputError from '@/components/input-error';
import TextLink from '@/components/text-link';
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 AuthLayout from '@/layouts/auth-layout';
import { register } from '@/routes';
import { request } from '@/routes/password';
import { LoaderCircle } from 'lucide-react';

interface LoginProps {
    status?: string;
    canResetPassword: boolean;
}

export default function Login({ status, canResetPassword }: LoginProps) {
    const [hasTriedSubmit, setHasTriedSubmit] = useState(false);
    const { t } = useTranslation('auth');

    const { data, setData, post, processing, errors, clearErrors } = useForm({
        email: '',
        password: '',
        remember: false,
    });

    const submit = (e: FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setHasTriedSubmit(true);
        post(window.location.pathname, {
            preserveScroll: true,
        });
    };

    useEffect(() => {
        if (!hasTriedSubmit) {
            return;
        }

        const errorKeys = Object.keys(errors);
        if (errorKeys.length === 0) {
            return;
        }

        const field = document.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(`[name="${errorKeys[0]}"]`);

        if (field) {
            field.scrollIntoView({ behavior: 'smooth', block: 'center' });
            field.focus();
        }
    }, [errors, hasTriedSubmit]);

    return (
        <AuthLayout title={t('login.title')} description={t('login.description')}>
            <Head title={t('login.title')} />

            <form onSubmit={submit} className="flex flex-col gap-6">
                <div className="grid gap-6">
                    <div className="grid gap-2">
                        <Label htmlFor="email">{t('login.email')}</Label>
                        <Input
                            id="email"
                            type="email"
                            name="email"
                            required
                            autoFocus
                            tabIndex={1}
                            autoComplete="email"
                            placeholder={t('login.email_placeholder')}
                            value={data.email}
                            onChange={(e) => {
                                setData('email', e.target.value);
                                if (errors.email) {
                                    clearErrors('email');
                                }
                            }}
                        />
                        <InputError key={`error-email`} message={errors.email} />
                    </div>

                    <div className="grid gap-2">
                        <div className="flex items-center">
                            <Label htmlFor="password">{t('login.password')}</Label>
                            {canResetPassword && (
                                <TextLink href={request()} className="ml-auto text-sm" tabIndex={5}>
                                    {t('login.forgot')}
                                </TextLink>
                            )}
                        </div>
                        <Input
                            id="password"
                            type="password"
                            name="password"
                            required
                            tabIndex={2}
                            autoComplete="current-password"
                            placeholder={t('login.password_placeholder')}
                            value={data.password}
                            onChange={(e) => {
                                setData('password', e.target.value);
                                if (errors.password) {
                                    clearErrors('password');
                                }
                            }}
                        />
                        <InputError key={`error-password`} message={errors.password} />
                    </div>

                    <div className="flex items-center space-x-3">
                        <Checkbox
                            id="remember"
                            name="remember"
                            tabIndex={3}
                            checked={data.remember}
                            onCheckedChange={(checked) => setData('remember', Boolean(checked))}
                        />
                        <Label htmlFor="remember">{t('login.remember')}</Label>
                    </div>

                    <Button type="submit" className="mt-4 w-full" tabIndex={4} disabled={processing}>
                        {processing && <LoaderCircle className="h-4 w-4 animate-spin" />}
                        {t('login.submit')}
                    </Button>
                </div>

                <div className="text-center text-sm text-muted-foreground">
                    {t('login.no_account')}{' '}
                    <TextLink href={register()} tabIndex={5}>
                        {t('login.sign_up')}
                    </TextLink>
                </div>
            </form>

            {status && <div className="mb-4 text-center text-sm font-medium text-green-600">{status}</div>}

            {Object.keys(errors).length > 0 && (
                <div key={`general-errors-${Object.keys(errors).join('-')}`} className="p-4 bg-red-50 border border-red-200 rounded-md mb-4">
                    <p className="text-sm text-red-800">
                        {Object.values(errors).join(' ')}
                    </p>
                </div>
            )}
        </AuthLayout>
    );
}
