import { Head, useForm, usePage, router } from '@inertiajs/react';
import AppLogoIcon from '@/components/app-logo-icon';
import { ShieldCheck } from 'lucide-react';

export default function EmailOtpChallenge() {
    const { email } = usePage().props as unknown as { email: string };
    const form = useForm({ code: '' });

    const submit = (e: React.FormEvent) => {
        e.preventDefault();
        form.post('/otp/verify');
    };

    return (
        <div className="flex min-h-dvh items-center justify-center bg-background px-6">
            <Head title="Verification code" />
            <div className="w-full max-w-sm">
                <div className="mb-6 flex flex-col items-center text-center">
                    <span className="flex size-11 items-center justify-center rounded-xl bg-primary text-primary-foreground">
                        <AppLogoIcon className="size-6" />
                    </span>
                    <h1 className="mt-4 flex items-center gap-2 text-xl font-semibold text-foreground">
                        <ShieldCheck className="size-5 text-primary" /> Check your email
                    </h1>
                    <p className="mt-1 text-sm text-muted-foreground">
                        We sent a 6-digit code to <strong>{email}</strong>.
                    </p>
                </div>

                <form onSubmit={submit} className="space-y-4">
                    <input
                        value={form.data.code}
                        onChange={(e) => form.setData('code', e.target.value.replace(/\D/g, '').slice(0, 6))}
                        inputMode="numeric" autoFocus placeholder="000000"
                        className="w-full rounded-md border border-border bg-background px-3 py-3 text-center text-2xl tracking-[0.5em] outline-none focus:border-primary" />
                    {form.errors.code && <p className="text-xs text-destructive">{form.errors.code}</p>}

                    <button type="submit" disabled={form.processing || form.data.code.length !== 6}
                        className="w-full rounded-md bg-primary py-2.5 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50">
                        Verify
                    </button>
                </form>

                <button onClick={() => router.post('/otp/resend')}
                    className="mt-4 w-full text-center text-sm text-muted-foreground hover:text-foreground">
                    Didn't get it? Send another code
                </button>
            </div>
        </div>
    );
}
