import Image from 'next/image';
import { useEffect, useState } from 'react';

import CountDown from '@/core/components/elements/CountDown/CountDown';
import ProductSlider from '@/lib/product/components/ProductSlider';

import { FlashSaleSkeleton } from '../skeleton/FlashSaleSkeleton';

const FlashSale = () => {
  const [flashSales, setFlashSales] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [duration, setDuration] = useState();
  const calculateRemainingTime = (endDate) => {
    const currentTime = new Date();
    const endTime = new Date(endDate);

    const remainingTimeInSeconds = (endTime - currentTime) / 1000;

    return Math.max(Math.round(remainingTimeInSeconds), 0);
  };
  useEffect(() => {
    const loadFlashSales = async () => {
      const res = await fetch('/api/flashsale-header');
      const { data } = await res.json();
      if (data) {
        setFlashSales(data);
        const remainingTime = calculateRemainingTime(data[0].endDate);
        setDuration(remainingTime);
      }
      setIsLoading(false);
    };

    loadFlashSales();
  }, []);

  if (isLoading) {
    return <FlashSaleSkeleton />;
  }

  return (
    <div className='sm:mt-4'>
      {flashSales?.length > 0 && (
        <div className='px-4 sm:px-0 grid grid-cols-1 gap-y-8 sm:mt-4'>
          {flashSales.map((flashSale, index) => (
            <div key={index}>
              <div className='flex gap-x-3 mb-4 justify-between sm:justify-start'>
                <div className='font-medium sm:text-h-lg mt-1.5'>
                  {flashSale.name}
                </div>
                <CountDown initialTime={duration} />
              </div>

              <div className='relative'>
                <Image
                  src={flashSale.banner}
                  alt={flashSale.name}
                  width={1080}
                  height={192}
                  className='w-full rounded mb-4 hidden sm:block'
                  loading='eager'
                />
                <Image
                  src={flashSale.bannerMobile}
                  alt={flashSale.name}
                  width={256}
                  height={48}
                  className='w-full rounded mb-4 block sm:hidden'
                  loading='eager'
                />
                <FlashSaleProduct
                  flashSaleId={flashSale.pricelistId}
                  duration={duration}
                />
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

const FlashSaleProduct = ({ flashSaleId, duration }) => {
  const [products, setProducts] = useState(null);
  useEffect(() => {
    const data_search = new URLSearchParams({
      query: `fq=flashsale_id_i:${flashSaleId}&fq=flashsale_price_f:[1 TO *]&limit=500&orderBy=flashsale-price-asc&source=similar`,
      operation: 'AND',
      duration: `${duration}`,
    });
    const loadProducts = async () => {
      const res = await fetch(
        `/api/search-flashsale?${data_search.toString()}`
      );
      const { data } = await res.json();
      setProducts(data.response);
    };

    loadProducts();
  }, []);

  return <ProductSlider products={products} />;
};

export default FlashSale;
