"use client";

import Image from "next/image";
import { useEffect, useState } from "react";

type ShowroomGalleryItem = {
  _key?: string;
  title: string;
  description?: string;
  layout?: "portrait" | "square" | "landscape" | "wide";
  coverImageUrl?: string | null;
  alt?: string;
  gallery: Array<{
    _key?: string;
    url?: string | null;
    alt?: string;
  }>;
};

type ShowroomGalleryProps = {
  slots: ShowroomGalleryItem[];
};

const layoutClassBySlot = {
  portrait: "aspect-[4/5]",
  square: "aspect-square",
  landscape: "aspect-[4/3] md:col-span-2",
  wide: "aspect-[16/9] md:col-span-3",
} as const;

export function ShowroomGallery({ slots }: ShowroomGalleryProps) {
  const [activeIndex, setActiveIndex] = useState<number | null>(null);
  const [activeImageIndex, setActiveImageIndex] = useState(0);

  const activeSlot = activeIndex !== null ? slots[activeIndex] : null;
  const activeImages = activeSlot?.gallery?.filter((item) => item.url) || [];

  useEffect(() => {
    if (activeIndex === null) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        setActiveIndex(null);
        return;
      }

      if (!activeImages.length) return;

      if (event.key === "ArrowRight") {
        setActiveImageIndex((current) => (current + 1) % activeImages.length);
      }

      if (event.key === "ArrowLeft") {
        setActiveImageIndex((current) => (current - 1 + activeImages.length) % activeImages.length);
      }
    };

    document.body.style.overflow = "hidden";
    window.addEventListener("keydown", onKeyDown);

    return () => {
      document.body.style.overflow = "";
      window.removeEventListener("keydown", onKeyDown);
    };
  }, [activeImages.length, activeIndex]);

  return (
    <>
      <section className="grid gap-4 md:grid-cols-3">
        {slots.map((slot, index) => {
          const imageUrl = slot.coverImageUrl || slot.gallery[0]?.url || null;
          const layout = slot.layout || "portrait";
          const layoutClass = layoutClassBySlot[layout] || layoutClassBySlot.portrait;
          const galleryCount = slot.gallery?.length || 0;
          const isClickable = galleryCount > 0;

          return (
            <article
              key={slot._key || `${slot.title}-${index}`}
              className={`overflow-hidden rounded-[1.7rem] border border-[#f0c9c9] bg-[linear-gradient(180deg,#fffefe_0%,#fff4f4_100%)]`}
            >
              {imageUrl ? (
                <button
                  type="button"
                  onClick={() => {
                    if (!isClickable) return;
                    setActiveIndex(index);
                    setActiveImageIndex(0);
                  }}
                  className={`h-full w-full text-left ${isClickable ? "cursor-zoom-in" : "cursor-default"}`}
                  aria-label={isClickable ? `Ouvrir la galerie ${slot.title}` : slot.alt || slot.title}
                  disabled={!isClickable}
                >
                  <div
                    className={`${layoutClass} bg-cover bg-center`}
                    style={{ backgroundImage: `url(${imageUrl})` }}
                    aria-label={slot.alt || slot.title}
                  >
                    <div className="h-full w-full" />
                  </div>
                  <div className="flex min-h-[7.4rem] flex-col justify-between gap-3 bg-[linear-gradient(180deg,#fff7f4_0%,#fff0ef_100%)] p-4 text-left">
                    <div className="space-y-2">
                      <h2 className="font-serif leading-[1.05] ">{slot.title}</h2>
                      {slot.description ? <p className="line-clamp-2 text-sm leading-relaxed text-[var(--muted)]">{slot.description}</p> : null}
                    </div>
                    <div className="flex items-center justify-between gap-3">
                      {galleryCount > 0 ? (
                        <p className="text-sm font-semibold text-[var(--accent-3)]">
                          {galleryCount} photo{galleryCount > 1 ? "s" : ""}
                        </p>
                      ) : (
                        <span />
                      )}
                      <span className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--accent-3)]">Voir</span>
                    </div>
                  </div>
                </button>
              ) : (
                <div className="flex h-full flex-col justify-between p-5">
                  <div className="inline-flex h-11 w-11 items-center justify-center rounded-full border border-[#f3d4d4] bg-white text-[var(--accent-3)]">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
                      <rect x="4" y="5" width="16" height="14" rx="2" />
                      <circle cx="9" cy="10" r="1.3" />
                      <path d="m7 16 3.5-3.5 2.5 2.5 2-2 2.5 3" />
                    </svg>
                  </div>
                  <div className="space-y-2">
                    {/* <p className="text-xs font-semibold uppercase tracking-[0.18em] text-[var(--accent-3)]">Emplacement {index + 1}</p> */}
                    <h2 className="font-serif text-2xl leading-tight text-[var(--foreground)]">{slot.title}</h2>
                    {galleryCount > 0 ? <p className="text-xs font-semibold uppercase tracking-[0.16em] text-[var(--accent-3)]">{galleryCount} photos</p> : null}
                    <p className="text-sm leading-relaxed text-[var(--muted)]">
                      {slot.description || "Zone reservee pour une photo du showroom."}
                    </p>
                  </div>
                </div>
              )}
            </article>
          );
        })}
      </section>

      {activeSlot && activeImages.length > 0 ? (
        <div
          className="fixed inset-0 z-50 flex items-center justify-center bg-[rgba(18,8,8,0.82)] p-4 backdrop-blur-sm"
          role="dialog"
          aria-modal="true"
          aria-label={`Galerie ${activeSlot.title}`}
          onClick={() => setActiveIndex(null)}
        >
          <div
            className="relative w-full max-w-6xl overflow-hidden rounded-[2rem] border border-white/12 bg-transparent"
            onClick={(event) => event.stopPropagation()}
          >
            <button
              type="button"
              onClick={() => setActiveIndex(null)}
              className="absolute right-4 top-4 z-20 inline-flex h-11 w-11 items-center justify-center rounded-full border border-white/12 bg-black/25 text-white transition hover:bg-black/45"
              aria-label="Fermer la galerie"
            >
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
                <path d="M6 6l12 12M18 6 6 18" />
              </svg>
            </button>

            <div className="grid gap-0 lg:grid-cols-[minmax(0,1fr)_320px]">
              <div className="relative flex min-h-[420px] items-center justify-center bg-transparent p-6 md:min-h-[640px]">
                {activeImages.length > 1 ? (
                  <>
                    <button
                      type="button"
                      onClick={() => setActiveImageIndex((current) => (current - 1 + activeImages.length) % activeImages.length)}
                      className="absolute left-4 top-1/2 z-10 inline-flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full border border-white/12 bg-black/25 text-white transition hover:bg-black/45"
                      aria-label="Image precedente"
                    >
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
                        <path d="m15 18-6-6 6-6" />
                      </svg>
                    </button>
                    <button
                      type="button"
                      onClick={() => setActiveImageIndex((current) => (current + 1) % activeImages.length)}
                      className="absolute right-4 top-1/2 z-10 inline-flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full border border-white/12 bg-black/25 text-white transition hover:bg-black/45"
                      aria-label="Image suivante"
                    >
                      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" className="h-5 w-5">
                        <path d="m9 18 6-6-6-6" />
                      </svg>
                    </button>
                  </>
                ) : null}

                <div className="relative h-[72vh] w-full max-w-4xl">
                  <Image
                    src={activeImages[activeImageIndex]?.url || ""}
                    alt={activeImages[activeImageIndex]?.alt || activeSlot.title}
                    fill
                    unoptimized
                    className="rounded-[1.5rem] object-contain"
                    sizes="(max-width: 1024px) 100vw, 70vw"
                  />
                </div>
              </div>

              <aside className="flex flex-col border-t border-white/10 bg-transparent lg:border-l lg:border-t-0">
                <div className="space-y-3 p-6 text-[var(--accent-3)]">
                  <p className="text-xs font-semibold uppercase tracking-[0.24em] text-[var(--accent-3)]">Showroom</p>
                  <h2 className="font-serif text-3xl leading-tight text-[var(--accent-3)]">{activeSlot.title}</h2>
                  <p className="text-sm font-semibold uppercase tracking-[0.18em] text-[var(--accent-3)]/80">
                    Photo {activeImageIndex + 1} sur {activeImages.length}
                  </p>
                  {activeSlot.description ? <p className="text-sm leading-relaxed text-[var(--accent-3)]/85">{activeSlot.description}</p> : null}
                </div>

                <div className="grid grid-cols-3 gap-3 border-t border-white/10 p-6 sm:grid-cols-4 lg:grid-cols-2">
                  {activeImages.map((image, index) => {
                    const isCurrent = index === activeImageIndex;
                    return (
                      <button
                        key={image._key || `${image.url}-${index}`}
                        type="button"
                        onClick={() => setActiveImageIndex(index)}
                        className={`overflow-hidden rounded-[1rem] border transition ${
                          isCurrent
                            ? "border-[#ffd6d6] ring-2 ring-[#ffd6d660]"
                            : "border-white/10 hover:border-white/25"
                        }`}
                        aria-label={`Voir la photo ${index + 1}`}
                      >
                        <div className="relative aspect-square h-full w-full">
                          <Image
                            src={image.url || ""}
                            alt={image.alt || activeSlot.title}
                            fill
                            unoptimized
                            className="object-cover"
                            sizes="160px"
                          />
                        </div>
                      </button>
                    );
                  })}
                </div>
              </aside>
            </div>
          </div>
        </div>
      ) : null}
    </>
  );
}
