import { useRef, useState } from 'react';
import { Swiper, SwiperSlide } from 'swiper/react';
import 'swiper/css';
import 'swiper/css/free-mode';
import 'swiper/css/pagination';
import ProductCard from './ProductCard';
import { Product } from '../../types/item';
import { A11y, Autoplay, Navigation, Pagination, Scrollbar } from 'swiper/modules';
import { Spin } from 'antd';



const ProductSwiper = ({data,isLoading}:any) => {
  const language = localStorage.getItem('language') ;
  
  const [swiperDirection, setSwiperDirection] = useState(language === "ar" ? "rtl" : "ltr");
  const swiperRef = useRef<any>(null);

  const BaseProducts = (data?.products as Product[]) || ([] as []);

  return (
    <div className='productSwiper'>
      <Swiper
        dir={swiperDirection}
        slidesPerView={5}
        spaceBetween={50}
        breakpoints={{
          0: { slidesPerView: 1 },
          400: { slidesPerView: 1 },
          600: { slidesPerView: 2 },
          900: { slidesPerView: 4 },
          1200: { slidesPerView: 4 },
          1500: { slidesPerView: 4  },
        }}
        modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay]}
        pagination={{ clickable: true }}
        className="mySwiper"
        onSwiper={(swiper:any) => (swiperRef.current = swiper)} // Store swiper instance
      >
        {
        isLoading ? <Spin/> :
        BaseProducts?.map((item:Product, index:number) => (
          <SwiperSlide key={index}>
            <ProductCard key={index} item={item} />
          </SwiperSlide>
        ))
        }
      </Swiper>
    </div>
  );
}

export default ProductSwiper;
