"use client";
import { useEffect, useMemo, useState } from "react";
import { BaseModal } from "@/components/modal";
import { useLocale, useTranslations } from "next-intl";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import type { AuctionItem } from "../types";

export default function MediaSection({ item }: { item: AuctionItem }) {
  const t = useTranslations("SINGLE_AUCTION.MEDIA");
  const locale = useLocale();
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [activeIndex, setActiveIndex] = useState(0);

  // 🧠 استخراج الصور الديناميكية من الـ API
  const images = useMemo(() => {
    const mainImage = item?.media_files?.main_image?.url;
    const extraImages = item?.media_files?.additional_images || [];

    // خلط الصورة  مع الصور الإضافية (بدون تكرار)
    const allImages = [
      ...(mainImage ? [mainImage] : []),
      ...extraImages
        .map((img) => img?.url)
        .filter((url): url is string => Boolean(url)),
    ];

    if (allImages.length === 0) {
      return [
        "https://upload.wikimedia.org/wikipedia/commons/5/54/Halterstandingshotarabianone.jpg",
      ];
    }

    return allImages as string[];
  }, [item]);

  useEffect(() => {
    if (!lightboxOpen) return;
    const onKeyDown = (e: KeyboardEvent) => {
      if (e.key === "Escape") {
        setLightboxOpen(false);
        return;
      }
      if (e.key === "ArrowLeft") {
        setActiveIndex((i) => (i - 1 + images.length) % images.length);
      }
      if (e.key === "ArrowRight") {
        setActiveIndex((i) => (i + 1) % images.length);
      }
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [images.length, lightboxOpen]);

  const openAt = (index: number) => {
    setActiveIndex(Math.max(0, Math.min(index, images.length - 1)));
    setLightboxOpen(true);
  };

  const goPrev = () =>
    setActiveIndex((i) => (i - 1 + images.length) % images.length);
  const goNext = () => setActiveIndex((i) => (i + 1) % images.length);

  return (
    <>
      <div className="bg-white rounded-2xl overflow-hidden border border-[#0F5132]/12 shadow-[0_12px_30px_rgba(15,81,50,0.08)]">
        <div className="relative">
          <img
            src={images[0]}
            onClick={() => openAt(0)}
            className="w-full h-80 sm:h-[26rem] object-cover cursor-zoom-in"
            alt={item?.camel?.name || t("lightbox_alt")}
          />
          <div className="absolute inset-x-0 bottom-0 h-20 bg-gradient-to-t from-black/55 to-transparent pointer-events-none" />
          <div className="absolute bottom-3 left-3">
            <span className="inline-flex items-center px-2.5 py-1 rounded-full bg-white/90 text-[#0F5132] text-xs font-bold">
              {locale === "ar" ? "معرض الصور" : "Gallery"}
            </span>
          </div>
        </div>

        {images.length > 1 && (
          <div className="p-4 grid grid-cols-3 sm:grid-cols-4 lg:grid-cols-5 gap-3 bg-slate-50/40 border-t border-slate-100">
            {images.map((src, i) => (
              <img
                key={i}
                src={src}
                onClick={() => {
                  openAt(i);
                }}
                className="h-20 w-full object-cover rounded-lg border border-slate-200 cursor-zoom-in hover:opacity-90 hover:shadow-md hover:border-[#0F5132]/30 transition"
                alt={t("thumb_alt", { index: i + 1 })}
              />
            ))}
          </div>
        )}
      </div>

      <BaseModal
        isOpen={lightboxOpen}
        onOpenChange={setLightboxOpen}
        size="full"
        contentClassName="p-0 bg-transparent"
      >
        <div className="fixed inset-0 bg-black/90 overflow-hidden">
          <button
            type="button"
            onClick={() => setLightboxOpen(false)}
            className="absolute top-4 right-4 z-10 inline-flex h-10 w-10 items-center justify-center rounded-full bg-white/10 text-white backdrop-blur transition hover:bg-white/15"
            aria-label={isRtl(locale) ? "إغلاق" : "Close"}
          >
            <X className="h-5 w-5" />
          </button>

          {images.length > 1 ? (
            <>
              <button
                type="button"
                onClick={goPrev}
                className="absolute left-3 top-1/2 z-10 -translate-y-1/2 inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white backdrop-blur transition hover:bg-white/15"
                aria-label={locale === "ar" ? "السابق" : "Previous"}
              >
                <ChevronLeft className="h-6 w-6" />
              </button>
              <button
                type="button"
                onClick={goNext}
                className="absolute right-3 top-1/2 z-10 -translate-y-1/2 inline-flex h-11 w-11 items-center justify-center rounded-full bg-white/10 text-white backdrop-blur transition hover:bg-white/15"
                aria-label={locale === "ar" ? "التالي" : "Next"}
              >
                <ChevronRight className="h-6 w-6" />
              </button>
            </>
          ) : null}

          <div className="flex h-full flex-col items-center justify-center p-0 pt-16 pb-24">
            <img
              src={images[activeIndex] || images[0]}
              alt={t("lightbox_alt")}
              className="w-auto max-w-[92vw] rounded-2xl object-contain shadow-[0_24px_80px_rgba(0,0,0,0.55)]"
              style={{
                // header ~64px + thumbnails bar ~88px + paddings
                maxHeight: images.length > 1 ? "calc(100vh - 180px)" : "calc(100vh - 110px)",
              }}
            />
          </div>

          {images.length > 1 ? (
            <div className="absolute inset-x-0 bottom-0 border-t border-white/10 bg-black/60 backdrop-blur">
              <div className="mx-auto max-w-5xl px-4 py-3 overflow-x-auto">
                <div className="flex items-center gap-2">
                  {images.map((src, i) => {
                    const active = i === activeIndex;
                    return (
                      <button
                        key={src + i}
                        type="button"
                        onClick={() => setActiveIndex(i)}
                        className={`relative h-14 w-20 flex-none overflow-hidden rounded-lg border transition ${
                          active
                            ? "border-white"
                            : "border-white/20 hover:border-white/40"
                        }`}
                        aria-label={t("thumb_alt", { index: i + 1 })}
                      >
                        <img
                          src={src}
                          alt={t("thumb_alt", { index: i + 1 })}
                          className="h-full w-full object-cover"
                        />
                        {active ? (
                          <span className="absolute inset-0 ring-2 ring-white/40" />
                        ) : null}
                      </button>
                    );
                  })}
                </div>
              </div>
            </div>
          ) : null}
        </div>
      </BaseModal>
    </>
  );
}

function isRtl(locale: string) {
  return locale === "ar";
}
