import { useHttp } from '@inertiajs/react';
import { useId, useRef, useState } from 'react';
import type { FormEvent } from 'react';
import { CategoryIcon } from '@/site/components/art/category-icon';
import { control, Field } from '@/site/components/sections/contact-form';
import { CrmForm } from '@/site/components/sections/crm-form';
import { Button } from '@/site/components/ui/button';
import { ArrowRight, Check } from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { Turnstile } from '@/site/components/ui/turnstile';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';

type Fields = {
    name: string;
    phone: string;
    email: 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;
};

/**
 * The stored request the later steps belong to: the number the CRM gave
 * it, or the token the site's own form received (contact.interest accepts
 * either).
 */
type Reference = { customer: number } | { lead: string };

type Step = 0 | 1 | 2;

type AppointmentWizardProps = {
    /** URL the site's own form posts the request to (contact.store). */
    action: string;
    /** URL the area and treatment chosen afterwards are posted to (contact.interest). */
    interestAction: string;
    privacyUrl: string;
    /** Public key of the "I am not a robot" check; null while it is off. */
    turnstile: string | null;
    className?: string;
};

/**
 * Appointment request in three short steps — the contact details first:
 *
 *  1. Details: the request form. It is sent right here, so the request is
 *     received even if the visitor stops at this point. With the CRM forms
 *     on it is the CRM's own form (a frame, K34); otherwise the site's
 *     (contact.store).
 *  2. Area and 3. treatment: optional answers that are added to the stored
 *     request (contact.interest) — to the request's row in the panel, or,
 *     for a CRM request, to a row kept under the CRM's number.
 *
 * Each step is a <fieldset> whose legend receives focus when it opens, so
 * keyboard and screen-reader users follow along.
 */
export function AppointmentWizard({
    action,
    interestAction,
    privacyUrl,
    turnstile,
    className,
}: AppointmentWizardProps) {
    const { nav, site } = useShared();
    const t = useT();
    const copy = t.home.appointment;
    const id = useId();
    const legends = useRef<(HTMLLegendElement | null)[]>([]);
    const finished = useRef<HTMLParagraphElement>(null);
    const [step, setStep] = useState<Step>(0);
    const [reference, setReference] = useState<Reference | null>(null);
    const [chosen, setChosen] = useState({ category: '', treatment: '' });
    const [done, setDone] = useState(false);
    const [failure, setFailure] = 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; lead?: string }>({
        name: '',
        phone: '',
        email: '',
        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 category = nav.categories.find(
        (item) => item.key === chosen.category,
    );
    const treatment = category?.treatments.find(
        (item) => item.key === chosen.treatment,
    );

    const go = (next: Step) => {
        setStep(next);
        // Focus the new step's legend once it is rendered.
        requestAnimationFrame(() => legends.current[next]?.focus());
    };

    const finish = () => {
        setDone(true);
        requestAnimationFrame(() => finished.current?.focus());
    };

    /** The request is stored: carry on with the optional questions. */
    const stored = (next: Reference | null) => {
        if (next === null) {
            // Nothing to attach the answers to.
            finish();

            return;
        }

        setReference(next);
        go(1);
    };

    /**
     * Add the choice to the stored request. It is sent in the background:
     * the request itself is already received, so a failure here costs the
     * visitor nothing and is not reported.
     */
    const save = (choice: { category: string; treatment: string }) => {
        setChosen(choice);

        if (reference === null) {
            return;
        }

        fetch(interestAction, {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ ...reference, ...choice }),
            keepalive: true,
        }).catch(() => {
            // See above.
        });
    };

    const chooseCategory = (key: string) => {
        // A treatment of another area no longer applies.
        save({ category: key, treatment: '' });
        go(2);
    };

    const chooseTreatment = (key: string) => {
        save({ category: chosen.category, treatment: key });
        finish();
    };

    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) =>
                stored(response?.lead ? { lead: response.lead } : null),
            // A refused token cannot be used again: ask for a new check.
            onError: (errors) => {
                if (errors.turnstile) {
                    form.setData('turnstile', '');
                    setCheck((count) => count + 1);
                }
            },
            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.
        });
    };

    const restart = () => {
        form.reset();
        form.clearErrors();
        setReference(null);
        setChosen({ category: '', treatment: '' });
        setDone(false);
        go(0);
    };

    // A light card on the dark section: it stands out, and error texts keep their contrast.
    const card = cx(
        'stage-light border-line bg-stage-2 relative rounded-xl border p-6 md:p-9',
        className,
    );

    if (done) {
        return (
            <div role="status" className={cx(card, 'flex flex-col gap-6')}>
                <span className="bg-accent-fg text-stage grid size-14 place-items-center rounded-full">
                    <Check className="size-7" />
                </span>
                <p
                    ref={finished}
                    tabIndex={-1}
                    className="font-display text-display-4 outline-none"
                >
                    {t.contact.form.successTitle}
                </p>
                <p className="text-soft text-lg">
                    {t.contact.form.successText}
                </p>
                {category ? (
                    <p className="text-soft flex flex-wrap items-center gap-x-2 gap-y-1 text-sm">
                        <span>{copy.chosen}:</span>
                        <span className="text-fg font-medium">
                            {treatment
                                ? `${category.name} — ${treatment.name}`
                                : category.name}
                        </span>
                    </p>
                ) : null}
                <Button
                    variant="outline"
                    onClick={restart}
                    className="self-start"
                >
                    {t.contact.form.another}
                </Button>
            </div>
        );
    }

    const steps = [copy.steps.details, copy.steps.area, copy.steps.treatment];
    const legendClass =
        'font-display text-display-4 outline-none focus-visible:underline';
    const field = (name: keyof Fields) => `${id}-${name}`;
    const errorId = (name: keyof Fields) => `${id}-${name}-error`;

    // Shown above the optional questions: the request is already with us.
    const received = (
        <p className="text-fg mb-6 flex items-center gap-3 text-[0.9375rem] font-medium">
            <span className="bg-accent-fg text-stage grid size-7 shrink-0 place-items-center rounded-full">
                <Check className="size-4" />
            </span>
            {copy.received}
        </p>
    );

    const progress = (
        <ol className="mb-8 grid grid-cols-3 gap-2">
            {steps.map((label, index) => (
                <li
                    key={label}
                    aria-current={index === step ? 'step' : undefined}
                    className="flex flex-col gap-2"
                >
                    <span className="bg-line h-0.5 overflow-hidden rounded-full">
                        <span
                            className={cx(
                                'bg-accent-fg ease-out-expo block h-full origin-left transition-transform duration-700 rtl:origin-right',
                                index <= step ? 'scale-x-100' : 'scale-x-0',
                            )}
                        />
                    </span>
                    <span
                        className={cx(
                            'text-eyebrow font-semibold uppercase transition-colors duration-500',
                            index <= step ? 'text-fg' : 'text-soft',
                        )}
                    >
                        <span className="sr-only">
                            {t.treatment.stepLabel(index + 1, 3)}:{' '}
                        </span>
                        {label}
                    </span>
                </li>
            ))}
        </ol>
    );

    const note = (
        <p className="text-soft border-line mt-8 flex items-start gap-2 border-t pt-5 text-xs">
            <ArrowRight className="mt-0.5 size-3.5 shrink-0" />
            {t.contact.note}
        </p>
    );

    // Steps two and three: the optional questions.
    const questions = (
        <>
            {received}
            {step === 1 ? (
                <fieldset className="wizard-step">
                    <legend
                        ref={(element) => {
                            legends.current[1] = element;
                        }}
                        tabIndex={-1}
                        className={legendClass}
                    >
                        {copy.areaQuestion}
                    </legend>
                    <p className="text-soft mt-2 text-[0.9375rem]">
                        {copy.optional}
                    </p>
                    <ul className="mt-6 grid grid-cols-2 gap-2.5 sm:grid-cols-3">
                        {nav.categories.map((item) => (
                            <li key={item.key} data-accent={item.accent}>
                                <button
                                    type="button"
                                    onClick={() => chooseCategory(item.key)}
                                    aria-pressed={chosen.category === item.key}
                                    className="group border-line hover:border-accent-fg aria-pressed:border-accent-fg aria-pressed:bg-stage-3 flex h-full w-full flex-col items-start gap-3 rounded-lg border p-4 text-start transition-colors duration-300"
                                >
                                    <CategoryIcon
                                        name={item.icon}
                                        className="text-accent-fg ease-out-expo size-8 transition-transform duration-500 group-hover:scale-110"
                                    />
                                    <span className="text-[0.9375rem] leading-snug font-medium">
                                        {item.name}
                                    </span>
                                </button>
                            </li>
                        ))}
                        <li>
                            <button
                                type="button"
                                onClick={finish}
                                className="border-line-strong hover:border-fg text-soft hover:text-fg flex h-full w-full items-center rounded-lg border border-dashed p-4 text-start text-[0.9375rem] transition-colors duration-300"
                            >
                                {copy.notSure}
                            </button>
                        </li>
                    </ul>
                </fieldset>
            ) : null}

            {step === 2 && category ? (
                <fieldset className="wizard-step" data-accent={category.accent}>
                    <legend
                        ref={(element) => {
                            legends.current[2] = element;
                        }}
                        tabIndex={-1}
                        className={legendClass}
                    >
                        {copy.treatmentQuestion}
                    </legend>
                    <p className="text-soft mt-2 flex items-center gap-2">
                        <CategoryIcon
                            name={category.icon}
                            className="text-accent-fg size-5"
                        />
                        {category.name}
                    </p>
                    <ul className="mt-6 flex flex-wrap gap-2">
                        {category.treatments.map((item) => (
                            <li key={item.key}>
                                <button
                                    type="button"
                                    onClick={() => chooseTreatment(item.key)}
                                    className="border-line-strong hover:border-accent-fg rounded-full border px-4 py-2.5 text-sm transition-colors duration-300"
                                >
                                    {item.name}
                                </button>
                            </li>
                        ))}
                    </ul>
                    <div className="mt-8 flex flex-wrap items-center justify-between gap-4">
                        <button
                            type="button"
                            onClick={() => go(1)}
                            className="text-soft hover:text-fg text-sm font-medium transition-colors"
                        >
                            ← {copy.back}
                        </button>
                        <Button variant="outline" onClick={finish}>
                            {copy.decideTogether}
                        </Button>
                    </div>
                </fieldset>
            ) : null}
        </>
    );

    // With the CRM forms on, the first step is the CRM's own form.
    if (site.crm) {
        return (
            <div role="group" aria-label={copy.formLabel} className={card}>
                {progress}
                {step === 0 ? (
                    <fieldset className="wizard-step">
                        <legend
                            ref={(element) => {
                                legends.current[0] = element;
                            }}
                            tabIndex={-1}
                            className={legendClass}
                        >
                            {copy.detailsQuestion}
                        </legend>
                        <CrmForm
                            config={site.crm}
                            kind="message"
                            onStored={(customer) =>
                                stored(customer === null ? null : { customer })
                            }
                            className="mt-6"
                        />
                    </fieldset>
                ) : (
                    questions
                )}
                {note}
            </div>
        );
    }

    return (
        <form
            onSubmit={submit}
            noValidate
            aria-label={copy.formLabel}
            className={card}
        >
            {progress}

            {step === 0 ? (
                <fieldset className="wizard-step">
                    <legend
                        ref={(element) => {
                            legends.current[0] = element;
                        }}
                        tabIndex={-1}
                        className={legendClass}
                    >
                        {copy.detailsQuestion}
                    </legend>

                    <div className="mt-6 grid gap-5 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')}
                            className="md:col-span-2"
                        >
                            <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('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={3}
                                maxLength={2000}
                                value={form.data.message}
                                onChange={(event) =>
                                    update('message', event.target.value)
                                }
                                aria-describedby={
                                    form.errors.message
                                        ? errorId('message')
                                        : `${id}-message-hint`
                                }
                                className={cx(control, 'resize-y')}
                            />
                        </Field>
                    </div>

                    {/* Honeypot: hidden from people and assistive technology. */}
                    <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>

                    <label className="text-soft mt-6 flex cursor-pointer items-start gap-4 text-sm">
                        <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}

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

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

                    <div className="mt-8 flex justify-end">
                        <Button
                            type="submit"
                            size="lg"
                            arrow
                            disabled={form.processing}
                        >
                            {form.processing
                                ? t.contact.form.sending
                                : t.contact.form.submit}
                        </Button>
                    </div>
                </fieldset>
            ) : (
                questions
            )}

            {note}
        </form>
    );
}
