"use client";

import { useEffect, useState } from "react";
import Image from "next/image";
import { ChevronLeft, ChevronRight, X } from "lucide-react";
import { FastAverageColor } from 'fast-average-color';


export default function ProductGallery({ images }) {
  const [selectedImage, setSelectedImage] = useState(images[0]);
  const [lightboxOpen, setLightboxOpen] = useState(false);
  const [lightboxIndex, setLightboxIndex] = useState(0);

  const openLightbox = (index) => {
    setLightboxIndex(index);
    setLightboxOpen(true);
  };

  const closeLightbox = () => {
    setLightboxOpen(false);
  };

  const nextImage = () => {
    setLightboxIndex((prevIndex) => (prevIndex + 1) % images.length);
  };

  const prevImage = () => {
    setLightboxIndex((prevIndex) => (prevIndex - 1 + images.length) % images.length);
  };

  useEffect(() => {
    const fac = new FastAverageColor();
    fac.getColorAsync(selectedImage.url)
      .then(color => {
        const container = document.querySelector("#container")
        console.log("color", color)
        // document.body.style.background = color.rgba
        // document.body.style.color = color.isDark ? '#fff' : '#000';
        container.style.backgroundColor = color.rgba;
        // container.style.color = color.isDark ? '#fff' : '#000';
      })
      .catch(e => {
        console.log(e);
      });
  }, [selectedImage])

  return (
    <div className="max-w-[500px] lg:min-w-[500px] pr-4 lg:border-r">
      <div className="aspect-w-1 aspect-h-1 w-full overflow-hidden" id="container">
        <Image
          src={selectedImage.url || "/placeholder.svg"}
          alt={selectedImage.alternativeText ?? ""}
          width={500}
          height={500}
          className="object-contain cursor-pointer aspect-square mx-auto"
          onClick={() => openLightbox(images.findIndex((img) => img.documentId === selectedImage.documentId))}
        />
      </div>
      <div className="mt-4 grid grid-cols-4 gap-1">
        {images.slice(0, 4).map((image) => (
          <Image
            key={image.documentId}
            src={image.url || "/placeholder.svg"}
            alt={image.alternativeText ?? ""}
            width={100}
            height={100}
            className={`object-cover cursor-pointer rounded-lg overflow-hidden ${selectedImage.documentId === image.documentId ? "ring-2 ring-primary/50" : ""
              }`}
            onClick={() => setSelectedImage(image)}
          />
        ))}
      </div>

      {lightboxOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center z-50">
          <div className="relative max-w-4xl w-full">
            {/* Close Button */}
            <button
              className="absolute top-4 right-4 p-2 rounded-full text-white hover:bg-gray-700 transition-colors bg-gray-400 shadow-lg"
              onClick={closeLightbox}
            >
              <X className="h-6 w-6" />
            </button>

            {/* Lightbox Image */}
            <Image
              src={images[lightboxIndex].url || "/placeholder.svg"}
              alt={images[lightboxIndex].alternativeText}
              width={1200}
              height={1200}
              className="object-contain w-full h-full"
            />

            {/* Previous Button */}
            <button
              className="absolute top-1/2 left-4 transform -translate-y-1/2 p-2 rounded-full text-white hover:bg-gray-700 transition-colors bg-gray-400 shadow-lg"
              onClick={prevImage}
            >
              <ChevronLeft className="h-8 w-8" />
            </button>

            {/* Next Button */}
            <button
              className="absolute top-1/2 right-4 transform -translate-y-1/2 p-2 rounded-full text-white hover:bg-gray-700 transition-colors bg-gray-400 shadow-lg"
              onClick={nextImage}
            >
              <ChevronRight className="h-8 w-8" />
            </button>
          </div>
        </div>
      )}
    </div>
  );
}