/**
 * @author: Multiqos
 * File: CustomLightbox.tsx
 * Description: This file contains the CustomLightbox component, which is a custom lightbox for displaying images.
 * It handles image navigation, closing the lightbox, and keyboard navigation.
 */
import Image from "next/image";
import React, { useEffect, useState } from "react";

interface CustomLightboxProps {
  images: any;
  startIndex: number;
  isOpen: boolean;
  onClose: () => void;
}

const CustomLightbox: React.FC<CustomLightboxProps> = ({
  images,
  startIndex,
  isOpen,
  onClose,
}) => {
  const [currentIndex, setCurrentIndex] = useState(startIndex);

  // Reset current index when props change
  useEffect(() => {
    setCurrentIndex(startIndex);
  }, [startIndex, isOpen]);

  // Add/remove overflow-hidden to body when lightbox opens/closes
  useEffect(() => {
    if (isOpen) {
      document.body.classList.add("overflow-hidden");
    } else {
      document.body.classList.remove("overflow-hidden");
    }

    // Cleanup function to ensure overflow-hidden is removed when component unmounts
    return () => {
      document.body.classList.remove("overflow-hidden");
    };
  }, [isOpen]);

  // Handle keyboard navigation
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      if (!isOpen) return;

      if (e.key === "ArrowLeft") {
        prevImage();
      } else if (e.key === "ArrowRight") {
        nextImage();
      } else if (e.key === "Escape") {
        onClose();
      }
    };

    window.addEventListener("keydown", handleKeyDown);
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [isOpen, currentIndex, onClose]);

  // Auto-scroll to keep active thumbnail visible
  useEffect(() => {
    if (isOpen) {
      const thumbnail = document.getElementById(`thumbnail-${currentIndex}`);
      if (thumbnail) {
        thumbnail.scrollIntoView({ behavior: "smooth", inline: "center" });
      }
    }
  }, [currentIndex, isOpen]);

  if (!isOpen) return null;

  const nextImage = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex === images?.length - 1 ? 0 : prevIndex + 1
    );
  };

  const prevImage = () => {
    setCurrentIndex((prevIndex) =>
      prevIndex === 0 ? images?.length - 1 : prevIndex - 1
    );
  };
  return (
    <div className="fixed inset-0 z-[999] bg-black">
      {/* Close button */}
      <button
        onClick={onClose}
        className="absolute top-4 right-4 h-[45px] w-[45px] flex justify-center items-center z-10"
      >
        <i className="Icon IconClose !w-[30px] !h-[30px] cursor-pointer !bg-white hover:!bg-primaryColor"></i>
      </button>

      {/* Main image */}
      <div className="relative inset-0 flex items-center justify-center p-4 h-[calc(100%-120px)]">
        <Image
          src={images[currentIndex]}
          alt="Preview"
          className="max-h-full max-w-full !w-full !h-full object-contain"
          height={2000}
          width={2000}
        />
        {/* Navigation arrows */}
        <button
          onClick={prevImage}
          className="absolute left-4 top-1/2 transform -translate-y-1/2 p-2 bg-primaryColor hover:bg-secondaryColor cursor-pointer h-[30px] md:h-[45px] w-[30px] md:w-[45px] flex justify-center items-center rounded-full hover:bg-opacity-70"
        >
          <i className="Icon IconBackArrow !w-[20px] !h-[20px] !bg-white"></i>
        </button>
        <button
          onClick={nextImage}
          className="absolute right-4 top-1/2 transform -translate-y-1/2 p-2 bg-primaryColor hover:bg-secondaryColor cursor-pointer h-[30px] md:h-[45px] w-[30px] md:w-[45px] flex justify-center items-center rounded-full hover:bg-opacity-70"
        >
          <i className="Icon IconFowrardArrow !w-[20px] !h-[20px] !bg-white"></i>
        </button>
      </div>

      {/* Thumbnail slider */}
      <div className="absolute bottom-0 left-0 right-0 h-[90px] bg-black bg-opacity-75 flex items-center overflow-x-hidden my-4">
        <div className="flex space-x-2 px-4 overflow-auto">
          {images?.map((img: any, index: number) => (
            <div
              id={`thumbnail-${index}`}
              key={index}
              className={`relative h-16 w-[70px] md:w-[120px] flex-shrink-0 bg-whiteFBColor cursor-pointer transition rounded-xs overflow-hidden mb-1 ${currentIndex === index ? "z-10" : "opacity-40 hover:opacity-100"
                }`}
              onClick={() => setCurrentIndex(index)}
            >
              <Image
                src={img}
                alt={`Thumbnail ${index}`}
                className="!h-full w-full object-cover"
                height={300}
                width={300}
              />
              {currentIndex === index && (
                <div className="absolute inset-0 border-2 border-primaryColor rounded-xs"></div>
              )}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default CustomLightbox;
