import { createFileRoute } from "@tanstack/react-router";
import { useEffect, useState } from "react";
import { Photo } from "@/components/site/look";
import { Frame, PageIntro } from "@/components/site/shell";
import { Modal } from "@/components/ui";
import { getGallery, getPreferredLocale } from "@/lib/clinic/api";
import { useI18n } from "@/lib/i18n/context";

const CATS = ["arrival", "reception", "consult", "treatment", "lounge", "amenities", "corridor"] as const;

export const Route = createFileRoute("/gallery")({
  loader: async () => getGallery({ data: await getPreferredLocale() }),
  component: GalleryPage,
});

function GalleryPage() {
  const initial = Route.useLoaderData();
  const { locale, t } = useI18n();
  const [data, setData] = useState(initial);
  const [cat, setCat] = useState<string>("all");
  const [index, setIndex] = useState<number | null>(null);
  useEffect(() => {
    if (data.locale === locale) return;
    let live = true;
    getGallery({ data: locale }).then((next) => { if (live) setData(next); });
    return () => { live = false; };
  }, [locale, data.locale]);
  const items = data.items.filter((item) => cat === "all" || item.category === cat);
  const current = index === null ? null : items[index];
  const label = (key: string) => {
    const map: Record<string, string> = {
      arrival: t("gallery.catArrival"),
      reception: t("gallery.catReception"),
      consult: t("gallery.catConsult"),
      treatment: t("gallery.catTreatment"),
      lounge: t("gallery.catLounge"),
      amenities: t("gallery.catAmenities"),
      corridor: t("gallery.catCorridor"),
    };
    return map[key] ?? key;
  };
  useEffect(() => {
    function onKey(event: KeyboardEvent) {
      if (index === null) return;
      if (event.key === "ArrowRight") setIndex((value) => (value === null ? value : (value + 1) % items.length));
      if (event.key === "ArrowLeft") setIndex((value) => (value === null ? value : (value - 1 + items.length) % items.length));
    }
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [index, items.length]);
  if (data.shell.flags.gallery === false) {
    return <Frame shell={data.shell}><p className="p-10">{t("errors.module")}</p></Frame>;
  }
  return (
    <Frame shell={data.shell}>
      <PageIntro kicker={t("gallery.kicker")} title={t("gallery.title")} lead={t("gallery.lead")} image="/clinic/lounge.jpg" />
      <div className="mx-auto flex max-w-7xl gap-2 overflow-x-auto px-5 md:px-6">
        <button type="button" className={`h-11 shrink-0 border-b px-2 text-sm tracking-wide ${cat === "all" ? "border-gold text-forest" : "border-transparent text-muted"}`} onClick={() => setCat("all")}>{t("common.all")}</button>
        {CATS.map((key) => (
          <button key={key} type="button" className={`h-11 shrink-0 border-b px-2 text-sm tracking-wide ${cat === key ? "border-gold text-forest" : "border-transparent text-muted"}`} onClick={() => setCat(key)}>{label(key)}</button>
        ))}
      </div>
      <div className="mx-auto grid max-w-7xl grid-cols-2 gap-3 px-4 py-6 md:grid-cols-3 md:px-6 lg:grid-cols-4">
        {items.map((item, itemIndex) => (
          <button key={item.id} type="button" className="text-start" onClick={() => setIndex(itemIndex)} aria-label={t("gallery.view")}>
            <Photo src={item.url} alt={item.caption} className="aspect-square w-full rounded-[1.35rem] object-cover" />
            <span className="mt-2 line-clamp-2 block text-sm text-muted">{item.caption}</span>
          </button>
        ))}
      </div>
      <Modal open={current !== null} onOpenChange={(open) => { if (!open) setIndex(null); }} title={current?.caption ?? t("gallery.title")}>
        {current ? (
          <div>
            <Photo src={current.url} alt={current.caption} className="max-h-[70vh] w-full rounded-md object-contain" />
            <div className="mt-3 flex justify-between">
              <button type="button" className="h-11 px-3" onClick={() => setIndex((value) => (value === null ? value : (value - 1 + items.length) % items.length))}>{t("gallery.prev")}</button>
              <button type="button" className="h-11 px-3" onClick={() => setIndex((value) => (value === null ? value : (value + 1) % items.length))}>{t("gallery.nextImage")}</button>
            </div>
          </div>
        ) : null}
      </Modal>
    </Frame>
  );
}
