import React, { useState, useEffect } from 'react';
import ProductPromoCard from '../../../../src-migrate/modules/product-promo/components/Card';
import { fetchPromoItemsSolr } from '../../../../src/api/promoApi';
import { Swiper, SwiperSlide } from 'swiper/react';
import useDevice from '@/core/hooks/useDevice';
import LogoSpinner from '../../../../src/core/components/elements/Spinner/LogoSpinner'

const PromoList = ({ selectedPromo }) => {
  const [title, setTitle] = useState('');
  const [slug, setSlug] = useState('');
  const [promoItems, setPromoItems] = useState([]);
  const [promoData, setPromoData] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const { isMobile } = useDevice();

  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]);

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

        console.log("selectedPromo",selectedPromo)
        console.log("slug",slug)
        console.log("items",items)
        console.log("promoItems",promoItems)

        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);
      // Reset the promoItems and promoData when slug changes
      setPromoItems([]);
      setPromoData([]);
      fetchPromotions();
    }
  }, [slug]);

  return (
    <div>
      <h1 className='text-h-sm md:text-h-lg  font-semibold py-4'>{title}</h1>
      {isLoading ? (
        <div className="loading-spinner flex justify-center">
          <LogoSpinner width={48} height={48} />
        </div>
      ) : (
        
        <Swiper slidesPerView={isMobile ? 1.5 : 3.25} spaceBetween={12} freeMode>
          {promoData?.map((promotion) => (
            <SwiperSlide key={promotion.id}>
              <div className="min-w-[380px] max-w-[380px] mb-[20px] sm:min-w-[330px] md:min-w-[360px] lg:min-w-[380px] xl:min-w-[380px]">
                <ProductPromoCard promotion={promotion} />
              </div>
            </SwiperSlide>
          ))}
        </Swiper>
      )}
    </div>
  );
};

export default PromoList;
