import React, { useState, useRef, useEffect} from 'react';
import Slider from 'react-slick'; 
import 'slick-carousel/slick/slick.css';
import 'slick-carousel/slick/slick-theme.css';
import Image from 'next/image';
import FloorPlanAttachmentService, {FloorPlanAttOPData} from "@/service/FloorPlanAttachmentService";
import {handleFetchWithTokenRefresh} from '@utils/common';
import { useCookies } from 'react-cookie';
import { Fancybox } from '@fancyapps/ui'; 
import "@fancyapps/ui/dist/fancybox/fancybox.css";
import { log } from 'console';

interface ProductSliderProps {
  floorPlanId: number;
}
const ProductSliderSlick: React.FC<ProductSliderProps> = ({floorPlanId}) => {
  const [thumbsSlider, setThumbsSlider] = useState<Slider | null>(null); 
  const [mainSlider, setMainSlider] = useState<Slider | null>(null);
  const [autoplayPaused, setAutoplayPaused] = useState(true);
  const [floorPlanattachmentData, setFloorPlanattachmentData] = useState<FloorPlanAttOPData | undefined>(undefined); 
  const [cookies, setCookie, removeCookie] = useCookies();
  const [loading, setLoading] = useState(true);

  const fetchAttachment = async () => {
    try {
      const FloorPlanattachmentData = await FloorPlanAttachmentService.getFloorPlanAttachmentByFloorPlanId(floorPlanId);
      if(FloorPlanattachmentData != undefined && FloorPlanattachmentData != null && FloorPlanattachmentData?.FloorPlanAttachmentsFind){
        setFloorPlanattachmentData(FloorPlanattachmentData);
      }
    } catch (err:any) {
      console.error('Error during fetch data:', err);
      handleFetchWithTokenRefresh(err, cookies, setCookie, fetchAttachment, err);
    }
    finally {
      setLoading(false); 
    }
  };

  
  useEffect(() => {
    fetchAttachment();
  },[floorPlanId]); 
  
  useEffect(() => {
    Fancybox.bind('[data-fancybox="gallery"]', {
      // You can configure additional Fancybox options here
      Carousel: {
        infinite: false,
      },
    });
    return () => {
      Fancybox.destroy(); // Clean up Fancybox when the component is unmounted
    };
  }, []);

   const numberOfImages = floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows?.length || 1; 
   const slidesToShow = numberOfImages < 4 ? numberOfImages : 4;

   const mainSliderSettings = {
    //infinite: true, 
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: numberOfImages > 1 ,
    autoplay: !autoplayPaused && numberOfImages > 1,
    autoplaySpeed: 5000,
    asNavFor: thumbsSlider || undefined, 
    dots: false, 
    
    beforeChange: (current: number, next: number) => {
      if (thumbsSlider) {
        thumbsSlider.slickGoTo(next); 
      }
    },
    afterChange: (index: number) => {
      if (thumbsSlider) {
        thumbsSlider.slickGoTo(0); 
      }
    },
    onClick: () => {
      setAutoplayPaused((prev) => !prev); 
    },
    focusOnSelect: false,
    //infinite: numberOfImages > 1,
    infinite:false,
    prevArrow: <div className="slick-prev custom-prev-arrow" />,
    nextArrow: <div className="slick-next custom-next-arrow" />,
  }; 


  const thumbsSliderSettings = {
  slidesToShow: 4,
  slidesToScroll: 1,
  focusOnSelect: true,
  asNavFor: mainSlider || undefined,
  watchOverflow: true,
  infinite: true,
  arrows:false,
  swipeToSlide: true,
  adaptiveHeight: false,
  accessibility: false,
  centerPadding: "0px",
  
  responsive: [
    {
      breakpoint: 768,
      settings: {
        slidesToShow: slidesToShow,
      },
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
      },
    },
  ],
};

  const renderImage = (url: string | undefined, index: number) => {
    
    return (
      <div key={index} className="slide d-flex align-items-center justify-content-center">
       <Image
         data-fancybox="gallery"
          className="slider-img  w-100"
          src={url || "/Images/no_photo.jpg"}
          alt={`slider-img-${index}`}
          width={1070}
          height={820}
        />
      </div>
    );
  };


  
  return (
    <div className="slider-area ">
      <div id="product__slider" tabIndex={-1}>
        <div className="row justify-content-center">
          <div className="col-xxl-10 col-xl-10 col-lg-12 col-md-12 col-sm-12 col-12">
            <Slider
              {...mainSliderSettings} className="product__slider-main mx-auto"
              ref={(slider) => setMainSlider(slider)}
            >
              {!loading && (
                (floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows && floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows?.length > 0 ? (
                  floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows.map((row, index) =>
                    renderImage(row?.file_attachment_url?.direct, index)
                  )
                ) : (
                  numberOfImages === 0 ?
                  renderImage("/Images/no_photo.jpg", 0) : null
                ))
              )}
            </Slider>
          </div>
        </div>
      </div>
      
      {numberOfImages > 1 && (
        <div className="product__slider-thmb " tabIndex={-1} >
          <Slider
          
            {...thumbsSliderSettings}
            ref={(slider) => setThumbsSlider(slider)}
          >

          {floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows && floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows?.length > 0 ? (
              floorPlanattachmentData?.FloorPlanAttachmentsFind?.rows.map((row, index) => (
                <div key={index} className="thumb" >
                  <Image
                      className="slider-img"
                      src={row?.file_attachment_url?.direct || " "}
                      alt="slider-thumb"
                      width={310}
                      height={210}
                    />
              </div>
              ))
            ) : null}
            
          </Slider>
        </div>  
        )}
    </div>
  );
};

export default ProductSliderSlick;
