import {
    useCallback,
    useEffect,
    useEffectEvent,
    useRef,
    useState,
} from 'react';
import { FormDone } from '@/site/components/sections/form-done';
import { useOnEnter } from '@/site/hooks/use-in-view';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import {
    crmCustomerId,
    crmFormAddress,
    crmFormCss,
    crmFormEvent,
    crmFormTokens,
    crmWhatsappNumber,
} from '@/site/lib/crm-form';
import type { CrmFormKind } from '@/site/lib/crm-form';
import { cx } from '@/site/lib/cx';
import type { CrmForms } from '@/site/types';

declare global {
    interface Window {
        /** Queue read by a tag manager, once one is installed. */
        dataLayer?: unknown[];
    }
}

/**
 * Height of the frame. The form page cannot report its own height, so each
 * kind reserves what its fields need at the two widths its layout knows
 * (see `crmFormCss`) — measured in the browser, with room for the consent
 * line to wrap. Change them together with the style sheet.
 */
const FRAME: Record<CrmFormKind, string> = {
    message: 'h-[33rem] @min-[560px]:h-[28rem]',
    whatsapp: 'h-[21.5rem] @min-[680px]:h-[15rem]',
};

/** Placeholder bars shown until the form page has loaded. */
const BARS: Record<CrmFormKind, number> = {
    message: 3,
    whatsapp: 2,
};

type CrmFormProps = {
    config: CrmForms;
    kind: CrmFormKind;
    /**
     * When the form page is requested: once the form comes `near` the
     * viewport (default) or `now` (a panel the visitor has just opened).
     */
    load?: 'near' | 'now';
    /**
     * Called once the CRM has stored the request, with the number it gave
     * it (null when it gave none). The caller then takes over; without it
     * the form shows its own confirmation.
     */
    onStored?: (customerId: number | null) => void;
    className?: string;
};

/**
 * A request form of the clinic's CRM: the CRM's own form page in a frame,
 * dressed in this site's tokens (docs/DECISIONS.md K34). The page posts to
 * the CRM itself; this component only learns that a request was stored and
 * then shows the confirmation — for the WhatsApp form with a link to the
 * chat with the number the CRM named, in case the browser kept the form
 * page from opening it. Without such a number there is no chat to offer:
 * the request is simply confirmed (the site links to no number of its own,
 * docs/DECISIONS.md K39).
 *
 * Nothing is requested from the CRM before `load` says so, and the frame's
 * height is reserved from the start, so the page never jumps.
 */
export function CrmForm({
    config,
    kind,
    load = 'near',
    onStored,
    className,
}: CrmFormProps) {
    const { locale } = useShared();
    const t = useT();
    const box = useRef<HTMLDivElement>(null);
    const frame = useRef<HTMLIFrameElement>(null);
    const [armed, setArmed] = useState(false);
    const [address, setAddress] = useState<string | null>(null);
    const [ready, setReady] = useState(false);
    const [done, setDone] = useState<{ whatsapp: string | null } | null>(null);

    const whatsapp = kind === 'whatsapp';
    const submit = whatsapp ? t.forms.whatsappSubmit : t.contact.form.submit;

    const arm = useCallback(() => setArmed(true), []);
    const stored = useEffectEvent((id: number | null) => onStored?.(id));
    const reports = onStored !== undefined;

    // `near`: the shared observer; `now` leaves it without a target.
    const unobserved = useRef<HTMLDivElement>(null);
    useOnEnter(load === 'near' ? box : unobserved, arm, '0px 0px 60% 0px');

    useEffect(() => {
        if (load !== 'now') {
            return;
        }

        const id = requestAnimationFrame(arm);

        return () => cancelAnimationFrame(id);
    }, [load, arm]);

    // The address carries the colours in effect around the frame, so it is
    // built in the browser, once the form is wanted.
    useEffect(() => {
        const element = box.current;

        if (!armed || !element) {
            return;
        }

        const id = requestAnimationFrame(() =>
            setAddress(
                crmFormAddress(config, {
                    kind,
                    locale,
                    texts: {
                        name: t.forms.name,
                        phone: t.forms.phone,
                        email: t.forms.email,
                        note: t.forms.note,
                        submit,
                    },
                    css: crmFormCss(crmFormTokens(element, kind), kind, submit),
                    page: location,
                }),
            ),
        );

        return () => cancelAnimationFrame(id);
    }, [armed, config, kind, locale, t, submit]);

    // The form page reports what happens inside it.
    useEffect(() => {
        if (!armed) {
            return;
        }

        let origin: string;

        try {
            origin = new URL(config.url).origin;
        } catch {
            return;
        }

        const receive = (message: MessageEvent) => {
            if (
                message.origin !== origin ||
                message.source !== frame.current?.contentWindow
            ) {
                return;
            }

            const event = crmFormEvent(message.data);

            if (!event) {
                return;
            }

            // The same events the CRM's own embed hands to a tag manager.
            (window.dataLayer ??= []).push(event);

            if (event.event !== 'formSubmitted') {
                return;
            }

            if (reports) {
                stored(crmCustomerId(event));
            } else {
                setDone({ whatsapp: crmWhatsappNumber(event) });
            }
        };

        addEventListener('message', receive);

        return () => removeEventListener('message', receive);
    }, [armed, config.url, reports]);

    const again = () => {
        setReady(false);
        setDone(null);
    };

    // The chat with the number the CRM assigned to the request.
    const chat =
        whatsapp && done?.whatsapp ? `https://wa.me/${done.whatsapp}` : null;

    return (
        <div className={cx('@container', className)}>
            <div ref={box} className={cx('relative', FRAME[kind])}>
                {done ? (
                    <FormDone
                        chat={chat}
                        onAgain={again}
                        className="h-full justify-center"
                    />
                ) : (
                    <>
                        {/* Stand-in for the fields until the form page is there. */}
                        <div
                            aria-hidden="true"
                            className={cx(
                                'crm-skeleton absolute inset-0 grid content-start gap-3 p-[3px] transition-opacity duration-500',
                                whatsapp && '@min-[680px]:grid-cols-3',
                                ready && 'opacity-0',
                            )}
                        >
                            {Array.from({ length: BARS[kind] }, (_, index) => (
                                <span
                                    key={index}
                                    className="border-line-strong h-13 rounded-md border"
                                />
                            ))}
                            <span className="bg-line h-13 rounded-full" />
                        </div>
                        <noscript>
                            <style>{'.crm-skeleton{display:none}'}</style>
                            <p className="text-soft">{t.forms.noscript}</p>
                        </noscript>
                        {address ? (
                            <iframe
                                ref={frame}
                                src={address}
                                title={
                                    whatsapp
                                        ? t.forms.whatsappFrame
                                        : t.forms.contactFrame
                                }
                                onLoad={() => setReady(true)}
                                className={cx(
                                    'absolute inset-0 size-full scheme-light transition-opacity duration-500',
                                    !ready && 'opacity-0',
                                )}
                            />
                        ) : null}
                    </>
                )}
            </div>
        </div>
    );
}
