import Image from 'next/image';
import { useEffect, useState } from 'react';
import CountDown from '@/core/components/elements/CountDown/CountDown';
import productSearchApi from '@/lib/product/api/productSearchApi';
import ProductSlider from '@/lib/product/components/ProductSlider';
import flashSaleApi from '../api/flashSaleApi';
import { FlashSaleSkeleton } from '../skeleton/FlashSaleSkeleton';
import Link from 'next/link';
import { useRouter } from 'next/router';
const FlashSaleNonDisplay = () => {
  const [flashSales, setFlashSales] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const router = useRouter();
  useEffect(() => {
    const loadFlashSales = async () => {
      const dataFlashSales = await flashSaleApi();
      setFlashSales(dataFlashSales);
      setIsLoading(false);
    };
    loadFlashSales();
  }, []);
  const handleSubmit = () => {
    router.push(`/shop/search?penawaran=${flashSales[0]?.pricelistId}`);
  };
  if (isLoading) {
    return <FlashSaleSkeleton />;
  }

  return (
    flashSales?.length > 0 && (
      <div className='px-4 sm:px-0 grid grid-cols-1 gap-y-8'>
        {flashSales.map((flashSale, index) => (
          <div key={index}>
            <div className='flex items-center mb-4 justify-between '>
              <div className='font-medium sm:text-h-lg mt-1.5'>
                Penawaran Terbatas
              </div>
              <div
                onClick={handleSubmit}
                className='!text-red-500 font-semibold cursor-pointer'
              >
                Lihat Semua
              </div>
            </div>
            <div className='relative'>
              <FlashSaleProduct flashSaleId={flashSale.pricelistId} />
            </div>
          </div>
        ))}
      </div>
    )
  );
};
const FlashSaleProduct = ({ flashSaleId }) => {
  const [products, setProducts] = useState(null);
  useEffect(() => {
    const loadProducts = async () => {
      const dataProducts = await productSearchApi({
        query: `fq=-flashsale_id_i:${flashSaleId}&fq=flashsale_price_f:[1 TO *]&limit=25&orderBy=flashsale-discount-desc`,
        operation: 'AND',
      });
      setProducts(dataProducts.response);
    };
    loadProducts();
  }, [flashSaleId]);
  return <ProductSlider products={products} />;
};
export default FlashSaleNonDisplay;
