"use client";

import { IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import BoldIcon from "@/components/ui/BoldIcon";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";

type ProductImageLightboxProps = {
  images: string[];
  initialIndex?: number;
  alt: string;
  open: boolean;
  onClose: () => void;
};

export default function ProductImageLightbox({
  images,
  initialIndex = 0,
  alt,
  open,
  onClose,
}: ProductImageLightboxProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [activeIndex, setActiveIndex] = useState(initialIndex);

  useEffect(() => {
    if (!open || !scrollRef.current) return;
    scrollRef.current.scrollTo({
      left: initialIndex * scrollRef.current.clientWidth,
      behavior: "auto",
    });
    setActiveIndex(initialIndex);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, initialIndex]);

  if (!open) return null;

  const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const el = event.currentTarget;
    const index = Math.round(el.scrollLeft / el.clientWidth);
    setActiveIndex(index);
  };

  return (
    <div className="fixed inset-0 z-[999] flex flex-col bg-black">
      <button
        type="button"
        onClick={onClose}
        aria-label="close"
        className="absolute right-4 top-4 z-10 flex h-9 w-9 items-center justify-center rounded-full bg-black/50"
      >
        <BoldIcon name="close-circle" size={22} tinted className="text-white" />
      </button>

      {images.length > 1 && (
        <span className="absolute left-1/2 top-4 z-10 -translate-x-1/2 rounded-full bg-black/50 px-2 py-0.5 text-[11px] font-bold text-white">
          {activeIndex + 1}/{images.length}
        </span>
      )}

      <div
        ref={scrollRef}
        onScroll={handleScroll}
        className="flex h-full w-full snap-x snap-mandatory overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
      >
        {images.map((img) => (
          <div key={img} className="relative h-full w-full shrink-0 snap-center">
            <Image
              src={IMAGE_BASE_URL + img}
              alt={alt}
              fill
              className="object-contain"
              sizes="100vw"
              unoptimized
            />
          </div>
        ))}
      </div>
    </div>
  );
}
