// productdetails/components/ProductGallery.tsx
"use client";

import { useEffect, useRef, useState } from "react";
import Swiper from "swiper";
import { Fancybox } from "@fancyapps/ui";
import "swiper/css";
import "swiper/css/navigation";
import "swiper/css/thumbs";
import "@fancyapps/ui/dist/fancybox/fancybox.css";

interface ProductGalleryProps {
  images: string[];
  variants?: any[];
  defaultImage?: string;
  selectedColor?: any;
}

export default function ProductGallery({
  images,
  variants,
  defaultImage,
  selectedColor,
}: ProductGalleryProps) {
  const [currentImages, setCurrentImages] = useState<string[]>([]);
  const mainSwiperRef = useRef<HTMLDivElement>(null);
  const thumbSwiperRef = useRef<HTMLDivElement>(null);
  const galleryRef = useRef<HTMLDivElement>(null);
  const [mainSwiper, setMainSwiper] = useState<Swiper | null>(null);
  const [thumbSwiper, setThumbSwiper] = useState<Swiper | null>(null);

  // Update images when selected color changes
  useEffect(() => {
    if (selectedColor && variants && variants.length > 0) {
      const matchedVariant = variants.find(
        (variant: any) => variant._id === selectedColor.id,
      );

      if (matchedVariant?.images && matchedVariant.images.length > 0) {
        const variantImages = matchedVariant.images.map((img: any) => img.url);
        setCurrentImages(variantImages);
        return;
      }
    }

    if (defaultImage) {
      setCurrentImages([defaultImage]);
      return;
    }

    if (images?.length > 0) {
      setCurrentImages(images);
      return;
    }

    setCurrentImages([]);
  }, [selectedColor, variants, images, defaultImage]);

  // Initialize Fancybox
  useEffect(() => {
    Fancybox.bind("[data-fancybox='gallery']", {
      on: {
        "Carousel.change": (fancybox: any) => {
          const index = fancybox.getSlide()?.index;

          if (typeof index === "number" && mainSwiper) {
            mainSwiper.slideTo(index);
          }
        },
      },
    });

    return () => {
      Fancybox.unbind("[data-fancybox='gallery']");
      Fancybox.close();
    };
  }, [currentImages, mainSwiper]);

  // Initialize Swiper when images change
  useEffect(() => {
    if (currentImages.length === 0) return;

    const timer = setTimeout(async () => {
      if (thumbSwiper) thumbSwiper.destroy(true, true);
      if (mainSwiper) mainSwiper.destroy(true, true);

      if (thumbSwiperRef.current && mainSwiperRef.current) {
        const { Navigation, Thumbs, FreeMode } = await import("swiper/modules");

        const thumbInstance = new Swiper(thumbSwiperRef.current, {
          modules: [Navigation, Thumbs, FreeMode],
          direction: "vertical",
          slidesPerView: 4,
          spaceBetween: 10,
          freeMode: true,
          watchSlidesProgress: true,
          slideToClickedSlide: true,
          navigation: {
            nextEl: ".swiper-button-next-thumbnail",
            prevEl: ".swiper-button-prev-thumbnail",
          },
          breakpoints: {
            1920: { slidesPerView: 5, spaceBetween: 20 },
            1700: { slidesPerView: 5, spaceBetween: 20 },
            1200: { slidesPerView: 5, spaceBetween: 10 },
            992: { slidesPerView: 5, spaceBetween: 10 },
            768: { slidesPerView: 4, spaceBetween: 10 },
            574: { slidesPerView: 4, spaceBetween: 10 },
            0: { slidesPerView: 4, spaceBetween: 10 },
          },
        });

        const mainInstance = new Swiper(mainSwiperRef.current, {
          modules: [Navigation, Thumbs],
          spaceBetween: 0,
          navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
          },
          thumbs: {
            swiper: thumbInstance,
          },
        });

        setThumbSwiper(thumbInstance);
        setMainSwiper(mainInstance);
      }
    }, 100);

    return () => {
      clearTimeout(timer);
      if (thumbSwiper) thumbSwiper.destroy(true, true);
      if (mainSwiper) mainSwiper.destroy(true, true);
    };
  }, [currentImages]);

  if (!currentImages.length) {
    return (
      <div className="detailsleftbx">
        <div className="gallery-container flex gap-4">
          <div className="no-image-placeholder rounded bg-gray-100 p-10 text-center">
            <p className="text-gray-500">No images available</p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="detailsleftbx" ref={galleryRef}>
      <div className="gallery-container flex gap-4">
        {/* Thumbnail Slider */}
        {currentImages.length > 1 && (
          <div className="swiper thumb-slider" ref={thumbSwiperRef}>
            <div className="swiper-wrapper">
              {currentImages.map((image, index) => (
                <div className="swiper-slide" key={index}>
                  <img
                    src={image}
                    alt={`Product thumbnail ${index + 1}`}
                    style={{ cursor: "pointer" }}
                  />
                </div>
              ))}
            </div>
            {currentImages.length > 4 && (
              <div className="swiper-nav">
                <div className="swiper-button-prev swiper-button-prev-thumbnail"></div>
                <div className="swiper-button-next swiper-button-next-thumbnail"></div>
              </div>
            )}
          </div>
        )}

        {/* Main Slider */}
        <div className="swiper main-slider" ref={mainSwiperRef}>
          <div className="swiper-wrapper">
            {currentImages.map((image, index) => (
              <div className="swiper-slide" key={index}>
                <img
                  data-fancybox="gallery"
                  data-src={image}
                  src={image}
                  alt={`Product image ${index + 1}`}
                  className="w-full cursor-pointer object-cover"
                />
              </div>
            ))}
          </div>
          {currentImages.length > 1 && <div className="swiper-nav"></div>}
        </div>
      </div>
    </div>
  );
}
