import { useHttp } from '@inertiajs/react';
import { useId, useState } from 'react';
import type { FormEvent, ReactNode } from 'react';
import { FormDone } from '@/site/components/sections/form-done';
import { Button } from '@/site/components/ui/button';
import { WhatsApp } from '@/site/components/ui/icons';
import { Turnstile } from '@/site/components/ui/turnstile';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { WhatsAppFormConfig } from '@/site/types';

type Fields = {
    name: string;
    phone: string;
    consent: boolean;
    /** Marks the request as one of this form (App\Enums\LeadChannel). */
    channel: 'whatsapp';
    /** Honeypot — must stay empty (App\Http\Requests\Site\StoreLeadRequest). */
    website: string;
    /** Token of the "I am not a robot" check (Cloudflare Turnstile). */
    turnstile: string;
};

const blank: Fields = {
    name: '',
    phone: '',
    consent: false,
    channel: 'whatsapp',
    website: '',
    turnstile: '',
};

/** Answer of contact.store to a request of this form. */
type Answer = {
    message: string;
    /** Address of the chat; null while the clinic's number is not set. */
    whatsapp?: string | null;
};

/**
 * The fields: a light surface on every stage, like those of the CRM's
 * form, so the form looks the same on the dark band and in the light panel.
 */
const field =
    'h-14 w-full rounded-md border border-line-strong bg-paper px-4.5 text-base text-ink transition-[border-color,box-shadow] duration-200 placeholder:text-mute focus:border-accent-fg focus:ring-3 focus:ring-accent-fg/25 focus:outline-none aria-invalid:border-danger';

/** From this width of the form on, name, phone and the button share a line. */
const wide = {
    cell: '@min-[680px]:col-span-4 @min-[680px]:row-start-1',
    button: '@min-[680px]:col-span-4 @min-[680px]:col-start-9 @min-[680px]:row-start-1',
    consent:
        '@min-[680px]:col-span-7 @min-[680px]:row-start-2 @min-[680px]:self-center',
    check: '@min-[680px]:col-span-5 @min-[680px]:row-start-2',
};

type WhatsAppFormProps = {
    config: WhatsAppFormConfig;
    className?: string;
};

/**
 * The site's own short form in front of WhatsApp, used while the CRM forms
 * are off (with them on, the CRM's form takes its place: `CrmForm`,
 * kind "whatsapp"). The visitor leaves a name and a phone number; the
 * request is stored in the panel (Talepler) and only its answer carries
 * the address of the chat — which then opens. Nothing on the site leads to
 * a WhatsApp number without this step (docs/DECISIONS.md K39).
 *
 * The layout follows the form's own width: one column in the panel of the
 * floating button, a single line on the home page's band.
 */
export function WhatsAppForm({ config, className }: WhatsAppFormProps) {
    const t = useT();
    const id = useId();
    const [failure, setFailure] = useState<string | null>(null);
    const [done, setDone] = useState<{ chat: string | null } | 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, Answer>(blank);

    // 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 (config.turnstile && !form.data.turnstile) {
            form.setError('turnstile', t.contact.form.robotRequired);

            return;
        }

        form.post(config.action, {
            onSuccess: (response) => {
                const chat = response?.whatsapp || null;

                setDone({ chat });

                // The request is stored: now, and only now, the chat opens.
                // A browser may keep the new tab closed; the confirmation
                // then offers the same address as a button.
                if (chat) {
                    window.open(chat, '_blank', 'noopener,noreferrer');
                }
            },
            // 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 (done) {
        return (
            <div className={className}>
                <FormDone
                    chat={done.chat}
                    onAgain={() => {
                        // Not reset(): after a stored request the form's
                        // defaults are what was sent.
                        form.setData(blank);
                        form.clearErrors();
                        setDone(null);
                    }}
                />
            </div>
        );
    }

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

    return (
        <div className={cx('@container', className)}>
            <noscript>
                <p className="text-soft">{t.forms.noscript}</p>
            </noscript>
            <form
                onSubmit={submit}
                noValidate
                aria-label={t.forms.whatsappFrame}
                className="needs-js relative grid grid-cols-12 items-start gap-3"
            >
                <div className={cx('col-span-12', wide.cell)}>
                    <label htmlFor={fieldId('name')} className="sr-only">
                        {t.contact.form.name}
                    </label>
                    <input
                        id={fieldId('name')}
                        type="text"
                        autoComplete="name"
                        required
                        placeholder={t.forms.name}
                        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={field}
                    />
                    <Problem id={errorId('name')}>{form.errors.name}</Problem>
                </div>

                <div className={cx('col-span-12', wide.cell)}>
                    <label htmlFor={fieldId('phone')} className="sr-only">
                        {t.contact.form.phone}
                    </label>
                    <input
                        id={fieldId('phone')}
                        type="tel"
                        inputMode="tel"
                        autoComplete="tel"
                        required
                        placeholder={t.forms.phone}
                        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={field}
                    />
                    <Problem id={errorId('phone')}>{form.errors.phone}</Problem>
                </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={fieldId('website')}>Website</label>
                    <input
                        id={fieldId('website')}
                        type="text"
                        tabIndex={-1}
                        autoComplete="off"
                        value={form.data.website}
                        onChange={(event) =>
                            form.setData('website', event.target.value)
                        }
                    />
                </div>

                <div className={cx('col-span-12', wide.consent)}>
                    <label className="text-soft flex cursor-pointer items-start gap-3 text-[0.8125rem] leading-snug">
                        <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-px size-[1.125rem] shrink-0 accent-(--accent-fg) scheme-light"
                        />
                        <span>
                            {t.contact.form.consentBefore}
                            {/* A new tab: what was typed stays where it is. */}
                            <a
                                href={config.privacyUrl}
                                target="_blank"
                                rel="noopener"
                                className="text-fg hover:text-accent-fg underline underline-offset-4"
                            >
                                {t.contact.form.consentLink}
                                <span className="sr-only">
                                    {' '}
                                    ({t.common.newTab})
                                </span>
                            </a>
                            {t.contact.form.consentAfter}
                        </span>
                    </label>
                    <Problem id={errorId('consent')}>
                        {form.errors.consent}
                    </Problem>
                    {/* Too many requests, no connection… (always in the page, so it is announced). */}
                    <div aria-live="polite">
                        {failure ? <Problem>{failure}</Problem> : null}
                    </div>
                </div>

                {config.turnstile ? (
                    <div className={cx('col-span-12', wide.check)}>
                        <Turnstile
                            key={check}
                            siteKey={config.turnstile}
                            onToken={(token) => update('turnstile', token)}
                            errorId={errorId('turnstile')}
                        />
                        <Problem id={errorId('turnstile')}>
                            {form.errors.turnstile}
                        </Problem>
                    </div>
                ) : null}

                <Button
                    type="submit"
                    variant="whatsapp"
                    size="lg"
                    disabled={form.processing}
                    className={cx('col-span-12 w-full', wide.button)}
                >
                    <span className="inline-flex items-center gap-2.5">
                        <WhatsApp className="size-[1.375rem]" />
                        {form.processing
                            ? t.contact.form.sending
                            : t.forms.whatsappSubmit}
                    </span>
                </Button>
            </form>
        </div>
    );
}

/**
 * An error text of the form. It brings its own light surface: the form
 * also stands on the dark band, where the error colour would not read.
 */
function Problem({ id, children }: { id?: string; children: ReactNode }) {
    if (!children) {
        return null;
    }

    return (
        <p
            id={id}
            className="border-danger/40 bg-paper text-danger mt-2 rounded-sm border px-3 py-1.5 text-sm"
        >
            {children}
        </p>
    );
}
