import { useHttp } from '@inertiajs/react';
import { useId, useState } from 'react';
import type { FormEvent, ReactNode } from 'react';
import { Button } from '@/site/components/ui/button';
import { Check } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { Turnstile } from '@/site/components/ui/turnstile';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';

export type TreatmentOptions = {
    label: string;
    items: { value: string; label: string }[];
}[];

type ContactFormProps = {
    /** URL the form posts to (the localized contact route). */
    action: string;
    options: TreatmentOptions;
    /** Treatment preselected through ?t=… on the contact URL. */
    selected: string | null;
    privacyUrl: string;
    /** Public key of the "I am not a robot" check; null while it is off. */
    turnstile: string | null;
};

type Fields = {
    name: string;
    phone: string;
    email: string;
    treatment: string;
    message: string;
    consent: boolean;
    /** Honeypot — must stay empty (App\Http\Requests\Site\StoreLeadRequest). */
    website: string;
    /** Token of the "I am not a robot" check (Cloudflare Turnstile). */
    turnstile: string;
};

export const control =
    'w-full rounded-md border border-line-strong bg-stage-2 px-4 py-3.5 text-base text-fg transition-colors duration-300 placeholder:text-soft/70 focus:border-accent-fg focus:outline-none aria-invalid:border-danger';

/**
 * Appointment / information request form.
 *
 * It posts JSON with Inertia's useHttp (a plain XHR, not a page visit):
 * the public site has no session, so validation errors come back as a 422
 * response instead of flashed data. Labels, errors and the success message
 * are announced to assistive technology.
 */
export function ContactForm({
    action,
    options,
    selected,
    privacyUrl,
    turnstile,
}: ContactFormProps) {
    const t = useT();
    const id = useId();
    const [failure, setFailure] = useState<string | null>(null);
    const [sent, setSent] = useState<string | null>(null);
    // Bumped to ask for a new robot check after the server refused a token.
    const [check, setCheck] = useState(0);

    const form = useHttp<Fields, { message: string }>({
        name: '',
        phone: '',
        email: '',
        treatment: selected ?? '',
        message: '',
        consent: false,
        website: '',
        turnstile: '',
    });

    // Correcting a field clears its error message right away.
    const update = <K extends keyof Fields>(name: K, value: Fields[K]) => {
        form.setData((data) => ({ ...data, [name]: value }));

        if (form.errors[name]) {
            form.clearErrors(name);
        }
    };

    const submit = (event: FormEvent) => {
        event.preventDefault();
        setFailure(null);

        // Without a token the request would only be refused (and count
        // against the rate limit).
        if (turnstile && !form.data.turnstile) {
            form.setError('turnstile', t.contact.form.robotRequired);

            return;
        }

        form.post(action, {
            onSuccess: (response) =>
                setSent(response?.message ?? t.contact.form.successText),
            // A refused token cannot be used again: ask for a new check.
            onError: (errors) => {
                if (errors.turnstile) {
                    form.setData('turnstile', '');
                    setCheck((count) => count + 1);
                }
            },
            // 429 (too many requests) and other non-validation failures.
            onHttpException: (response) => {
                let message = t.contact.form.error;

                try {
                    message =
                        (JSON.parse(response.data) as { message?: string })
                            .message ?? message;
                } catch {
                    // Not JSON — keep the generic message.
                }

                setFailure(message);
            },
            onNetworkError: () => setFailure(t.contact.form.error),
        }).catch(() => {
            // Already reported through the callbacks above.
        });
    };

    if (sent !== null) {
        return (
            <div
                role="status"
                className="border-line bg-stage-2 flex flex-col items-start gap-6 rounded-xl border p-8 md:p-12"
            >
                <span className="bg-accent-fg text-stage grid size-14 place-items-center rounded-full">
                    <Check className="size-7" />
                </span>
                <h2 className="font-display text-display-4">
                    {t.contact.form.successTitle}
                </h2>
                <p className="text-soft text-lg">{sent}</p>
                <Button
                    variant="outline"
                    onClick={() => {
                        form.reset();
                        form.clearErrors();
                        setSent(null);
                    }}
                >
                    {t.contact.form.another}
                </Button>
            </div>
        );
    }

    const field = (name: keyof Fields) => `${id}-${name}`;
    const errorId = (name: keyof Fields) => `${id}-${name}-error`;

    return (
        <form
            onSubmit={submit}
            noValidate
            aria-labelledby={`${id}-legend`}
            className="border-line bg-stage-2 rounded-xl border p-6 md:p-10"
        >
            <h2 id={`${id}-legend`} className="font-display text-display-4">
                {t.contact.form.legend}
            </h2>

            <div className="mt-10 grid gap-6 md:grid-cols-2">
                <Field
                    id={field('name')}
                    label={t.contact.form.name}
                    error={form.errors.name}
                    errorId={errorId('name')}
                >
                    <input
                        id={field('name')}
                        type="text"
                        autoComplete="name"
                        required
                        value={form.data.name}
                        onChange={(event) => update('name', event.target.value)}
                        aria-invalid={form.errors.name ? true : undefined}
                        aria-describedby={
                            form.errors.name ? errorId('name') : undefined
                        }
                        className={control}
                    />
                </Field>

                <Field
                    id={field('phone')}
                    label={t.contact.form.phone}
                    error={form.errors.phone}
                    errorId={errorId('phone')}
                >
                    <input
                        id={field('phone')}
                        type="tel"
                        inputMode="tel"
                        autoComplete="tel"
                        required
                        value={form.data.phone}
                        onChange={(event) =>
                            update('phone', event.target.value)
                        }
                        aria-invalid={form.errors.phone ? true : undefined}
                        aria-describedby={
                            form.errors.phone ? errorId('phone') : undefined
                        }
                        className={control}
                    />
                </Field>

                <Field
                    id={field('email')}
                    label={t.contact.form.email}
                    optional={t.contact.form.optional}
                    error={form.errors.email}
                    errorId={errorId('email')}
                >
                    <input
                        id={field('email')}
                        type="email"
                        autoComplete="email"
                        value={form.data.email}
                        onChange={(event) =>
                            update('email', event.target.value)
                        }
                        aria-invalid={form.errors.email ? true : undefined}
                        aria-describedby={
                            form.errors.email ? errorId('email') : undefined
                        }
                        className={control}
                    />
                </Field>

                <Field
                    id={field('treatment')}
                    label={t.contact.form.treatment}
                    optional={t.contact.form.optional}
                    error={form.errors.treatment}
                    errorId={errorId('treatment')}
                >
                    <select
                        id={field('treatment')}
                        value={form.data.treatment}
                        onChange={(event) =>
                            update('treatment', event.target.value)
                        }
                        className={cx(control, 'appearance-auto')}
                    >
                        <option value="">
                            {t.contact.form.treatmentPlaceholder}
                        </option>
                        {options.map((group) => (
                            <optgroup key={group.label} label={group.label}>
                                {group.items.map((item) => (
                                    <option key={item.value} value={item.value}>
                                        {item.label}
                                    </option>
                                ))}
                            </optgroup>
                        ))}
                    </select>
                </Field>

                <Field
                    id={field('message')}
                    label={t.contact.form.message}
                    optional={t.contact.form.optional}
                    hint={t.contact.form.messageHint}
                    hintId={`${id}-message-hint`}
                    error={form.errors.message}
                    errorId={errorId('message')}
                    className="md:col-span-2"
                >
                    <textarea
                        id={field('message')}
                        rows={5}
                        maxLength={2000}
                        value={form.data.message}
                        onChange={(event) =>
                            update('message', event.target.value)
                        }
                        aria-invalid={form.errors.message ? true : undefined}
                        aria-describedby={
                            form.errors.message
                                ? errorId('message')
                                : `${id}-message-hint`
                        }
                        className={cx(control, 'resize-y')}
                    />
                </Field>
            </div>

            {/* Honeypot: hidden from people and assistive technology, tempting for bots. */}
            <div
                aria-hidden="true"
                className="absolute -left-[9999px] size-px overflow-hidden"
            >
                <label htmlFor={field('website')}>Website</label>
                <input
                    id={field('website')}
                    type="text"
                    tabIndex={-1}
                    autoComplete="off"
                    value={form.data.website}
                    onChange={(event) =>
                        form.setData('website', event.target.value)
                    }
                />
            </div>

            <div className="mt-8">
                <label className="text-soft flex cursor-pointer items-start gap-4 text-[0.9375rem]">
                    <input
                        type="checkbox"
                        required
                        checked={form.data.consent}
                        onChange={(event) =>
                            update('consent', event.target.checked)
                        }
                        aria-invalid={form.errors.consent ? true : undefined}
                        aria-describedby={
                            form.errors.consent ? errorId('consent') : undefined
                        }
                        className="mt-0.5 size-5 shrink-0 accent-(--accent-fg)"
                    />
                    <span>
                        {t.contact.form.consentBefore}
                        <SiteLink
                            href={privacyUrl}
                            className="text-fg hover:text-accent-fg underline underline-offset-4"
                        >
                            {t.contact.form.consentLink}
                        </SiteLink>
                        {t.contact.form.consentAfter}
                    </span>
                </label>
                {form.errors.consent ? (
                    <p
                        id={errorId('consent')}
                        className="text-danger mt-2 text-sm"
                    >
                        {form.errors.consent}
                    </p>
                ) : null}
            </div>

            {turnstile ? (
                <Turnstile
                    key={check}
                    siteKey={turnstile}
                    onToken={(token) => update('turnstile', token)}
                    error={form.errors.turnstile}
                    errorId={errorId('turnstile')}
                    className="mt-8"
                />
            ) : null}

            <div aria-live="polite" className="mt-8">
                {failure || form.hasErrors ? (
                    <p className="border-danger/40 bg-danger/5 text-danger mb-6 rounded-md border px-4 py-3 text-[0.9375rem]">
                        {failure ?? t.contact.form.error}
                    </p>
                ) : null}
            </div>

            <Button type="submit" size="lg" arrow disabled={form.processing}>
                {form.processing
                    ? t.contact.form.sending
                    : t.contact.form.submit}
            </Button>
        </form>
    );
}

export type FieldProps = {
    id: string;
    label: string;
    children: ReactNode;
    optional?: string;
    hint?: string;
    hintId?: string;
    error?: string;
    errorId: string;
    className?: string;
};

export function Field({
    id,
    label,
    children,
    optional,
    hint,
    hintId,
    error,
    errorId,
    className,
}: FieldProps) {
    return (
        <div className={className}>
            <label
                htmlFor={id}
                className="mb-2 flex items-baseline justify-between gap-4 text-sm font-medium"
            >
                {label}
                {optional ? (
                    <span className="text-soft text-xs font-normal">
                        {optional}
                    </span>
                ) : null}
            </label>
            {children}
            {hint ? (
                <p id={hintId} className="text-soft mt-2 text-sm">
                    {hint}
                </p>
            ) : null}
            {error ? (
                <p id={errorId} className="text-danger mt-2 text-sm">
                    {error}
                </p>
            ) : null}
        </div>
    );
}
