"use client";

import { useState, useCallback } from "react";
import Image from "next/image";
import { X, ChevronLeft, ChevronRight } from "lucide-react";
import type { ServiceDetailImage } from "@/services/pages/public/services";

const ServiceImageGallery = ({
  images,
  title,
}: {
  images: ServiceDetailImage[];
  title: string;
}) => {
  const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);

  const openLightbox = (index: number) => setLightboxIndex(index);
  const closeLightbox = () => setLightboxIndex(null);

  const goPrev = useCallback(() => {
    if (lightboxIndex === null) return;
    setLightboxIndex((lightboxIndex - 1 + images.length) % images.length);
  }, [lightboxIndex, images.length]);

  const goNext = useCallback(() => {
    if (lightboxIndex === null) return;
    setLightboxIndex((lightboxIndex + 1) % images.length);
  }, [lightboxIndex, images.length]);

  const handleKeyDown = useCallback(
    (e: React.KeyboardEvent) => {
      if (e.key === "ArrowLeft") goPrev();
      if (e.key === "ArrowRight") goNext();
      if (e.key === "Escape") closeLightbox();
    },
    [goPrev, goNext]
  );

  // Duplicate for seamless infinite scroll (same as Clients section)
  const scrollImages = [...images, ...images];

  return (
    <>
      {/* Auto-scrolling strip */}
      <div className="overflow-hidden -mx-4 sm:-mx-8 lg:-mx-16 xl:-mx-24">
        <div className="flex animate-scroll-left gap-5 py-2">
          {scrollImages.map((img, i) => (
            <button
              key={`${img.public_id}-${i}`}
              onClick={() => openLightbox(i % images.length)}
              className="flex-shrink-0 relative w-[420px] h-64 overflow-hidden rounded-sm group focus:outline-none focus-visible:ring-2 focus-visible:ring-accent"
              aria-label={`View ${title} image ${(i % images.length) + 1}`}
            >
              <Image
                src={img.url}
                alt={`${title} ${(i % images.length) + 1}`}
                fill
                className="object-cover transition-transform duration-700 group-hover:scale-105"
                loading="lazy"
              />
              {/* Hover overlay */}
              <div className="absolute inset-0 bg-primary/0 group-hover:bg-primary/30 transition-colors duration-300 flex items-center justify-center">
                <span className="opacity-0 group-hover:opacity-100 transition-opacity duration-300 text-primary-foreground text-xs font-bold uppercase tracking-widest border border-primary-foreground/60 px-3 py-1.5 rounded-sm backdrop-blur-sm">
                  View
                </span>
              </div>
            </button>
          ))}
        </div>
      </div>

      {/* Lightbox */}
      {lightboxIndex !== null && (
        <div
          role="dialog"
          aria-modal="true"
          aria-label="Image viewer"
          className="fixed inset-0 z-50 bg-black/95 flex items-center justify-center"
          onKeyDown={handleKeyDown}
          tabIndex={-1}
        >
          {/* Close */}
          <button
            onClick={closeLightbox}
            className="absolute top-4 right-4 text-white/70 hover:text-white transition-colors p-2"
            aria-label="Close"
          >
            <X size={28} />
          </button>

          {/* Counter */}
          <span className="absolute top-5 left-1/2 -translate-x-1/2 text-white/60 text-sm font-medium tabular-nums">
            {lightboxIndex + 1} / {images.length}
          </span>

          {/* Prev */}
          <button
            onClick={goPrev}
            className="absolute left-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white transition-colors p-3 hover:bg-white/10 rounded-sm"
            aria-label="Previous image"
          >
            <ChevronLeft size={36} />
          </button>

          {/* Image */}
          <div className="relative w-[90vw] max-w-5xl h-[80vh]">
            <Image
              src={images[lightboxIndex].url}
              alt={`${title} ${lightboxIndex + 1}`}
              fill
              className="object-contain"
              priority
            />
          </div>

          {/* Next */}
          <button
            onClick={goNext}
            className="absolute right-4 top-1/2 -translate-y-1/2 text-white/70 hover:text-white transition-colors p-3 hover:bg-white/10 rounded-sm"
            aria-label="Next image"
          >
            <ChevronRight size={36} />
          </button>

          {/* Thumbnail strip */}
          {images.length > 1 && (
            <div className="absolute bottom-6 left-1/2 -translate-x-1/2 flex gap-2 max-w-[90vw] overflow-x-auto pb-1">
              {images.map((img, i) => (
                <button
                  key={img.public_id}
                  onClick={() => setLightboxIndex(i)}
                  className={`flex-shrink-0 relative w-16 h-10 overflow-hidden rounded-sm transition-all duration-200 ${
                    i === lightboxIndex
                      ? "ring-2 ring-accent opacity-100"
                      : "opacity-40 hover:opacity-70"
                  }`}
                  aria-label={`Go to image ${i + 1}`}
                >
                  <Image
                    src={img.url}
                    alt={`Thumbnail ${i + 1}`}
                    fill
                    className="object-cover"
                  />
                </button>
              ))}
            </div>
          )}
        </div>
      )}
    </>
  );
};

export default ServiceImageGallery;
