import { useEffect, useState } from 'react'
import flashSaleApi from '../api/flashSaleApi'
import Image from 'next/image'
import CountDown from '@/core/components/elements/CountDown/CountDown'
import productSearchApi from '@/lib/product/api/productSearchApi'
import ProductSlider from '@/lib/product/components/ProductSlider'
import { FlashSaleSkeleton } from '../skeleton/FlashSaleSkeleton'

const FlashSale = () => {
  const [flashSales, setFlashSales] = useState(null)
  const [isLoading, setIsLoading] = useState(true)

  useEffect(() => {
    const loadFlashSales = async () => {
      const dataFlashSales = await flashSaleApi()
      setFlashSales(dataFlashSales)
      setIsLoading(false)
    }
    loadFlashSales()
  }, [])

  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 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={flashSale.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'
              />
              <Image
                src={flashSale.bannerMobile}
                alt={flashSale.name}
                width={256}
                height={48}
                className='w-full rounded mb-4 block sm:hidden'
              />
              <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=500&orderBy=flashsale-price-asc`,
        operation: 'AND'
      })
      setProducts(dataProducts.response)
    }
    loadProducts()
  }, [flashSaleId])

  return <ProductSlider products={products} />
}

export default FlashSale
