import { Head, Link, useForm, usePage } from '@inertiajs/react';
import type { FormEvent } from 'react';

type PageProps = {
    wedding: { name: string } | null;
    emailHint: string | null;
};

export default function VerifyCode() {
    const { wedding, emailHint } = usePage<PageProps>().props;
    const form = useForm({ code: '' });

    const submit = (event: FormEvent) => {
        event.preventDefault();
        form.post('/login/verify');
    };

    return (
        <>
            <Head title="Code eingeben" />
            <main className="auth-shell">
                <section className="auth-card">
                    <Link className="back-link" href="/login">← Andere E-Mail-Adresse</Link>
                    <span className="eyebrow">{wedding?.name}</span>
                    <h1 className="auth-title">Fast geschafft</h1>
                    <p className="auth-copy">
                        Wir haben einen Code an <strong>{emailHint}</strong> gesendet. Er ist zehn Minuten gültig.
                    </p>

                    <form onSubmit={submit} noValidate>
                        <div className="mb-4">
                            <label className="form-label" htmlFor="code">Sechsstelliger Code</label>
                            <input
                                aria-describedby="code-help"
                                autoComplete="one-time-code"
                                autoFocus
                                className={`form-control code-input ${form.errors.code ? 'is-invalid' : ''}`}
                                id="code"
                                inputMode="numeric"
                                maxLength={6}
                                onChange={(event) => form.setData('code', event.target.value.replace(/\D/g, '').slice(0, 6))}
                                pattern="[0-9]{6}"
                                type="text"
                                value={form.data.code}
                            />
                            {form.errors.code
                                ? <div className="invalid-feedback">{form.errors.code}</div>
                                : <div className="form-text" id="code-help">Du kannst den Code direkt aus der E-Mail kopieren.</div>}
                        </div>

                        <button className="primary-action w-100" disabled={form.processing || form.data.code.length !== 6} type="submit">
                            {form.processing ? 'Wird geprüft …' : 'Sicher anmelden'}
                        </button>
                    </form>
                </section>
            </main>
        </>
    );
}
