import React, { useRef, useEffect } from "react";
import Slider from "react-slick";
import { SlArrowLeft, SlArrowRight } from "react-icons/sl";
import Image from "next/image";

import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";

interface ImageModalProps {
  isModalOpens: boolean;
  closeModal: () => void; // Corrected type for closeModal
  selectedIndex: number;
  viewListingData: { images: string[] };
  handleImageClick: (image: string) => void;
}

const ImageModal: React.FC<ImageModalProps> = ({
  isModalOpens,
  closeModal,
  selectedIndex,
  viewListingData,
  handleImageClick,
}) => {
  const sliderRef = useRef<Slider | null>(null);
  const thumbSliderRef = useRef<Slider | null>(null);

  useEffect(() => {
    if (isModalOpens) {
      if (sliderRef.current) {
        sliderRef.current.slickGoTo(selectedIndex, true);
      }
      if (thumbSliderRef.current) {
        thumbSliderRef.current.slickGoTo(selectedIndex, true);
      }
    }
  }, [isModalOpens, selectedIndex]);

  if (!isModalOpens) return null;

  return (
    <div
      className="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center z-50"
      onClick={closeModal}
    >
      <div
        className="relative bg-black p-4 bg-opacity-90 flex flex-col rounded-lg w-full h-full"
        onClick={(e) => e.stopPropagation()}
      >
        {/* Close Button */}
        <button
          className="absolute top-4 md:right-4 xs:right-0 text-white text-2xl z-10 md:p-4 xs:p-2"
          onClick={closeModal}
        >
          ✕
        </button>

        {/* Main Image Slider */}
        <div className="flex-1 flex justify-center items-center relative">
          <Slider
            ref={(slider) => {
              sliderRef.current = slider;
            }}
            dots={false}
            infinite={true}
            speed={500}
            slidesToShow={1}
            slidesToScroll={1}
            arrows={false}
            initialSlide={selectedIndex}
            className="w-full max-w-4xl md:h-[70vh] flex justify-center relative"
          >
            {viewListingData?.images.map((image: string, index: number) => (
              <div
                key={index}
                className="flex justify-center items-center relative w-full md:h-[70vh]"
              >
                <div className="relative w-full h-[70vh]">
                  <Image
                    src={image}
                    alt={`Slide ${index}`}
                    layout="fill"
                    objectFit="contain"
                    className="rounded-lg"
                    unoptimized // Only use unoptimized if absolutely necessary
                    // --- Add priority for the initially visible image ---
                    priority={index === selectedIndex}
                    // Consider adding fetchPriority if the image is critical for above-the-fold content
                    // fetchPriority={index === selectedIndex ? "high" : "auto"}
                  />
                </div>
              </div>
            ))}
          </Slider>

          {/* Navigation Buttons (existing code) */}
          <button
            className="absolute left-6 top-1/2 transform -translate-y-1/2 bg-gray-200 p-4 shadow-lg hover:bg-yellow-300 rounded-full hidden md:block"
            onClick={(e) => {
              e.stopPropagation();
              sliderRef.current?.slickPrev();
            }}
          >
            <SlArrowLeft />
          </button>
          <button
            className="absolute right-6 top-1/2 transform -translate-y-1/2 bg-gray-200 p-4 rounded-full shadow-lg hover:bg-yellow-300 hidden md:block"
            onClick={(e) => {
              e.stopPropagation();
              sliderRef.current?.slickNext();
            }}
          >
            <SlArrowRight />
          </button>
        </div>

        {/* Thumbnail Slider (existing code, no changes needed for preloading here typically) */}
        <div className="w-full max-w-7xl mx-auto mt-4">
          <Slider
            ref={(thumbSlider) => {
              thumbSliderRef.current = thumbSlider;
            }}
            dots={false}
            slidesToShow={Math.min(viewListingData?.images.length, 7)}
            slidesToScroll={1}
            arrows={false}
            autoplay={true}
            autoplaySpeed={3000}
            responsive={[
              {
                breakpoint: 640,
                settings: {
                  slidesToShow: Math.min(viewListingData?.images.length, 2),
                  infinite: true,
                  speed: 3000,
                },
              },
              {
                breakpoint: 1024,
                settings: {
                  slidesToShow: Math.min(viewListingData?.images.length, 6),
                  infinite: true,
                  speed: 3000,
                },
              },
              {
                breakpoint: 1440,
                settings: {
                  slidesToShow: Math.min(viewListingData?.images.length, 4),
                  infinite: true,
                  speed: 3000,
                },
              },
            ]}
          >
            {viewListingData?.images.map((image: string, index: number) => (
              <div key={index} className="px-1">
                <div className="flex justify-center">
                  <div
                    className={`relative h-24 md:h-32 w-40 cursor-pointer rounded-md mx-auto ${
                      viewListingData.images[selectedIndex] === image
                        ? "border-2 border-blue-500"
                        : ""
                    }`}
                    onClick={(e) => {
                      e.stopPropagation();
                      handleImageClick(image);
                      sliderRef.current?.slickGoTo(index);
                    }}
                  >
                    <Image
                      unoptimized
                      src={image}
                      alt={`Thumbnail ${index}`}
                      fill
                      className="rounded-md object-cover"
                    />
                  </div>
                </div>
              </div>
            ))}
          </Slider>

          {/* Navigation Buttons for Thumbnails (existing code) */}
          <button
            className="absolute left-28 bottom-6 transform -translate-y-1/2 bg-gray-200 p-4 shadow-lg hover:bg-yellow-300 rounded-full hidden md:block"
            onClick={(e) => {
              e.stopPropagation();
              thumbSliderRef.current?.slickPrev();
            }}
          >
            <SlArrowLeft />
          </button>
          <button
            className="absolute right-28 bottom-6 transform -translate-y-1/2 bg-gray-200 p-4 rounded-full shadow-lg hover:bg-yellow-300 hidden md:block"
            onClick={(e) => {
              e.stopPropagation();
              thumbSliderRef.current?.slickNext();
            }}
          >
            <SlArrowRight />
          </button>
        </div>
      </div>
    </div>
  );
};

export default ImageModal;
