// Components
import { Head } from '@inertiajs/react';
import { LoaderCircle } from 'lucide-react';
import type { FormEvent } from 'react';
import InputError from '@/components/InputError';
import TextLink from '@/components/TextLink';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useYupForm } from '@/hooks/use-yup-form';
import { forgotPasswordSchema } from '@/lib/validation/auth';
import { login } from '@/routes';
import { email as emailRoute } from '@/routes/password';

export default function ForgotPassword() {
    const { data, setData, processing, errors, validateField, submit } =
        useYupForm(forgotPasswordSchema, { email: '' });

    const handleSubmit = (e: FormEvent) => {
        e.preventDefault();

        submit((form) => form.post(emailRoute().url));
    };

    return (
        <>
            <Head title="Forgot password" />

            <div className="space-y-6">
                <form onSubmit={handleSubmit} noValidate>
                    <div className="grid gap-2">
                        <Label htmlFor="email">Email address</Label>
                        <Input
                            id="email"
                            type="email"
                            name="email"
                            value={data.email}
                            onChange={(e) => setData('email', e.target.value)}
                            onBlur={() => validateField('email')}
                            autoComplete="off"
                            autoFocus
                            placeholder="email@example.com"
                        />

                        <InputError message={errors.email} />
                    </div>

                    <div className="my-6 flex items-center justify-start">
                        <Button
                            className="w-full"
                            disabled={processing}
                            data-test="email-password-reset-link-button"
                        >
                            {processing && (
                                <LoaderCircle className="h-4 w-4 animate-spin" />
                            )}
                            Email password reset link
                        </Button>
                    </div>
                </form>

                <div className="space-x-1 text-center text-sm text-muted-foreground">
                    <span>Or, return to</span>
                    <TextLink href={login()}>log in</TextLink>
                </div>
            </div>
        </>
    );
}

ForgotPassword.layout = {
    title: 'Forgot password',
    description: 'Enter your email to receive a password reset link',
};
