import style from "../styles/section.module.css"

import React from 'react'
import { useQuery } from 'react-query'
import { Button, Skeleton } from '@chakra-ui/react'

import ProductPromoCard from './Card'
import { IPromotion } from '~/types/promotion'
import ProductPromoModal from "./Modal"
import { useModalStore } from "../stores/useModalStore"
import clsxm from "~/libs/clsxm"

type Props = {
  productId: number
}

const ProductPromoSection = ({ productId }: Props) => {
  const promotionsQuery = useQuery(
    `promotions-highlight:${productId}`,
    async () => await fetch(`/api/product-variant/${productId}/promotion/highlight`).then((res) => res.json()) as { data: IPromotion[] },
  )

  const promotions = promotionsQuery.data

  const { openModal } = useModalStore()

  return (
    <div className={clsxm('w-full overflow-y-hidden transition-all duration-500 h-0', {
      'h-[425px]': promotions?.data && promotions?.data.length > 0,
    })}>
      <ProductPromoModal />

      {promotions?.data && promotions?.data.length > 0 && (
        <div className={style.titleWrapper}>
          <span className={style.title}>Promo Tersedia</span>
          <Button colorScheme="yellow" type='button' onClick={() => openModal(productId)}>
            Lihat Semua
          </Button>
        </div>
      )}

      <Skeleton
        isLoaded={promotionsQuery.isSuccess}
        className={clsxm(
          "flex gap-x-4 overflow-x-auto px-4 md:px-0", {
          "min-h-[340px]": promotions?.data && promotions?.data.length > 0
        })}
      >
        {promotions?.data.map((promotion) => (
          <div key={promotion.id} className="min-w-[400px] max-w-[400px]">
            <ProductPromoCard promotion={promotion} />
          </div>
        ))}
      </Skeleton>
    </div>
  )
}

export default ProductPromoSection