import React, { useEffect, useState } from 'react';
import { Button, Skeleton } from '@chakra-ui/react'
import clsxm from "~/libs/clsxm"
import ProductPromoCard from '../../product-promo/components/Card';
import { fetchPromoItemsSolr } from '../../../../src/api/promoApi';
import { Swiper, SwiperSlide } from 'swiper/react';
import SwiperCore, { Navigation, Pagination } from 'swiper';
import useDevice from '@/core/hooks/useDevice';
import LogoSpinner from '../../../../src/core/components/elements/Spinner/LogoSpinner';
import usePromoStore from './promoStore';
import Link from "next/link"
import { IPromotion } from '~/types/promotion';
interface PromoListProps {
  selectedPromo: string; // Tipe selectedPromo ditetapkan sebagai string
}

const PromoList: React.FC<PromoListProps> = ({ selectedPromo }) => {
  const {
    title,
    slug,
    promoItems,
    promoData,
    isLoading,
    setTitle,
    setSlug,
    setPromoItems,
    setPromoData,
    setIsLoading,
  } = usePromoStore();

  const { isMobile, isDesktop } = useDevice();

  const swiperBanner = {
    modules: [Navigation],
    className: 'h-[400px] w-full',
    slidesPerView: isMobile ? 1.1 : 3.25,
    spaceBetween: 10,
    navigation:isMobile? true : false,
    allowTouchMove:isMobile? false : true,
  };

  useEffect(() => {
    if (selectedPromo === 'Bundling') {
      setTitle('Kombinasi Kilat Pilihan Kami!');
      setSlug('bundling');
    } else if (selectedPromo === 'Loading') {
      setTitle('Belanja Borong Pilihan Kami!');
      setSlug('discount_loading');
    } else if (selectedPromo === 'Merchandise') {
      setTitle('Gratis Merchandise Spesial Indoteknik');
      setSlug('merchandise');
    }
  }, [selectedPromo, setTitle, setSlug]);

  useEffect(() => {
    const fetchPromotions = async () => {
      setIsLoading(true);
      try {
        const items = await fetchPromoItemsSolr(`type_value_s:${slug}`, 0, 10); 
        setPromoItems(items);

        const promoDataPromises = items.map(async (item) => {
          try {
            const response = await fetchPromoItemsSolr(`id:${item.id}`, 0, 10);
            return response;
          } catch (fetchError) {
            return [];
          }
        });

        const promoDataArray = await Promise.all(promoDataPromises);
        const mergedPromoData = promoDataArray.reduce((accumulator, currentValue) => accumulator.concat(currentValue), []);
        setPromoData(mergedPromoData);

      } catch (error) {
        console.error('Error fetching promo items:', error);
      } finally {
        setIsLoading(false);
      }
    };

    if (slug) {
      setIsLoading(true);
      setPromoItems([]);
      setPromoData([]);
      fetchPromotions();
    }
  }, [slug, setPromoItems, setPromoData, setIsLoading]);

  return (
    <div className='min-h-[360px]'>
      <div className='flex justify-between  items-center'>
        <h1 className='text-h-sm md:text-h-lg font-semibold py-4'>{title}</h1>
        <div>
          <Link href={`/shop/promo/${slug}`} className='!text-red-500 font-semibold'>
            Lihat Semua
          </Link>
        </div>
      </div>
      {isLoading ? (
        <div className="loading-spinner flex justify-center">
          <LogoSpinner width={48} height={48} />
        </div>
      ) : (
        <Skeleton
        isLoaded={!isLoading}
        className={clsxm(
          "flex gap-x-4 overflow-x-auto px-4 md:px-0", {
          "min-h-[340px]": promoData[0] && promoData?.length > 0
        })}
      >
        {isDesktop && (
                    <Swiper {...swiperBanner}>
                      {promoData?.map((promotion: IPromotion) => (
                      <SwiperSlide key={promotion.id}>
                        <div className="min-w-36 max-w-[400px] mb-[20px] sm:w-full md:w-full lg:w-full xl:w-full">
                          <ProductPromoCard promotion={promotion} />
                        </div>
                      </SwiperSlide>
                    ))}
                  </Swiper>
        )}
        {isMobile && (promoData?.map((promotion: IPromotion) => (
          <div key={promotion.id} className="min-w-[400px] max-w-[400px]">
            <ProductPromoCard promotion={promotion}  />
          </div>
        )))}
        
      </Skeleton>
      )}
    </div>
  );
};

export default PromoList;