import { useEffect, useRef, useState } from 'react';
import type { KeyboardEvent } from 'react';
import { Picture } from '@/site/components/media/picture';
import { Reveal } from '@/site/components/motion/reveal';
import { ArrowRight, Close } from '@/site/components/ui/icons';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import type { GalleryPhoto } from '@/site/types';

type ClinicGalleryProps = {
    photos: GalleryPhoto[];
    /**
     * `mosaic`: a few large tiles of different sizes (home page);
     * `grid`: every photo in even rows (about page).
     */
    layout?: 'mosaic' | 'grid';
    className?: string;
};

/** Tile shapes of the mosaic, in order (12-column grid, on large screens). */
const mosaic = [
    'lg:col-span-7 lg:row-span-2',
    'lg:col-span-5',
    'lg:col-span-5',
    'lg:col-span-4',
    'lg:col-span-4',
    'lg:col-span-4',
];

/**
 * Photos of the clinic. Each tile drifts gently inside its frame while the
 * section scrolls past (`.gallery-tile` in site.css, driven by the nearest
 * scene) and opens a full-size view on click: a native <dialog> with
 * previous / next and keyboard arrows. Without JavaScript the tiles are
 * plain images with their captions.
 */
export function ClinicGallery({
    photos,
    layout = 'grid',
    className,
}: ClinicGalleryProps) {
    const t = useT();
    const dialog = useRef<HTMLDialogElement>(null);
    const [open, setOpen] = useState<number | null>(null);
    const shown = layout === 'mosaic' ? photos.slice(0, mosaic.length) : photos;

    useEffect(() => {
        const element = dialog.current;

        if (open === null || !element || element.open) {
            return;
        }

        element.showModal();
    }, [open]);

    const step = (by: number) =>
        setOpen((current) =>
            current === null
                ? current
                : (current + by + photos.length) % photos.length,
        );

    const onKeyDown = (event: KeyboardEvent<HTMLDialogElement>) => {
        if (event.key === 'ArrowRight') {
            step(document.dir === 'rtl' ? -1 : 1);
        } else if (event.key === 'ArrowLeft') {
            step(document.dir === 'rtl' ? 1 : -1);
        }
    };

    if (shown.length === 0) {
        return null;
    }

    const current = open === null ? null : photos[open];

    return (
        <>
            <ul
                className={cx(
                    'grid gap-3 sm:grid-cols-2 md:gap-4',
                    layout === 'mosaic'
                        ? 'lg:auto-rows-[minmax(14rem,19vw)] lg:grid-cols-12'
                        : 'lg:grid-cols-3',
                    className,
                )}
            >
                {shown.map((photo, index) => (
                    <Reveal
                        as="li"
                        key={photo.key}
                        delay={(index % 3) * 70}
                        className={cx(
                            'relative',
                            layout === 'mosaic' && mosaic[index],
                            layout === 'mosaic'
                                ? 'aspect-[4/3] lg:aspect-auto'
                                : 'aspect-[4/3]',
                        )}
                    >
                        <button
                            type="button"
                            onClick={() => setOpen(index)}
                            className="group gallery-tile border-line relative block size-full overflow-hidden rounded-lg border text-start"
                        >
                            <Picture
                                media={photo.media}
                                sizes={
                                    layout === 'mosaic' && index === 0
                                        ? '(min-width: 64rem) 58vw, (min-width: 40rem) 50vw, 100vw'
                                        : '(min-width: 64rem) 34vw, (min-width: 40rem) 50vw, 100vw'
                                }
                                className="gallery-image"
                            />
                            <span className="from-ink/85 text-bone absolute inset-x-0 bottom-0 bg-linear-to-t to-transparent px-5 pt-12 pb-4 text-[0.9375rem] font-medium">
                                {photo.caption}
                            </span>
                            <span className="sr-only"> — {t.gallery.open}</span>
                        </button>
                    </Reveal>
                ))}
            </ul>

            <dialog
                ref={dialog}
                aria-label={t.gallery.viewer}
                onClose={() => setOpen(null)}
                onKeyDown={onKeyDown}
                onClick={(event) => {
                    // A click on the backdrop (the dialog itself) closes it.
                    if (event.target === event.currentTarget) {
                        event.currentTarget.close();
                    }
                }}
                className="gallery-dialog stage-dark m-auto max-h-[92dvh] w-[min(92vw,80rem)] max-w-none overflow-visible bg-transparent p-0"
            >
                {current && open !== null ? (
                    <figure className="flex flex-col gap-4">
                        <div className="bg-ink-2 relative overflow-hidden rounded-lg">
                            <Picture
                                media={current.media}
                                sizes="92vw"
                                fit="contain"
                                className="max-h-[78dvh]"
                            />
                        </div>
                        <figcaption className="flex items-center justify-between gap-6 text-sm">
                            <span>
                                <span className="text-fg font-medium">
                                    {current.caption}
                                </span>
                                <span className="text-soft ms-3 tabular-nums">
                                    {t.gallery.position(
                                        open + 1,
                                        photos.length,
                                    )}
                                </span>
                            </span>
                            <span className="flex gap-2">
                                <button
                                    type="button"
                                    aria-label={t.common.showPrevious}
                                    onClick={() => step(-1)}
                                    className="border-line-strong hover:bg-fg hover:text-stage grid size-11 place-items-center rounded-full border transition-colors"
                                >
                                    <ArrowRight className="size-5 rotate-180 rtl:rotate-0" />
                                </button>
                                <button
                                    type="button"
                                    aria-label={t.common.showNext}
                                    onClick={() => step(1)}
                                    className="border-line-strong hover:bg-fg hover:text-stage grid size-11 place-items-center rounded-full border transition-colors"
                                >
                                    <ArrowRight className="size-5 rtl:rotate-180" />
                                </button>
                                <button
                                    type="button"
                                    aria-label={t.common.close}
                                    onClick={() => dialog.current?.close()}
                                    className="border-line-strong hover:bg-fg hover:text-stage grid size-11 place-items-center rounded-full border transition-colors"
                                >
                                    <Close className="size-5" />
                                </button>
                            </span>
                        </figcaption>
                    </figure>
                ) : null}
            </dialog>
        </>
    );
}
