import style from '../styles/card-countdown.module.css'

import React, { useEffect, useState } from 'react'
import { useQuery } from 'react-query'
import { ClockIcon } from 'lucide-react'
import { Skeleton } from '@chakra-ui/react'
import moment from 'moment'

import clsxm from '~/libs/clsxm'
import { IPromotion } from '~/types/promotion'
import { getPromotionProgram } from '~/services/promotionProgram'

type Props = {
  promotion: IPromotion
}

const ProductPromoCardCountdown = ({ promotion }: Props) => {
  const query = useQuery(['promotion-program', promotion.program_id], async () => {
    return await getPromotionProgram(promotion.program_id)
  })

  const program = query.data?.data || null

  const [count, setCount] = useState(program?.time_left || 0);

  useEffect(() => {
    let interval: NodeJS.Timeout;

    if (program?.time_left && program?.time_left > 0) {
      setCount(program?.time_left);

      interval = setInterval(() => {
        setCount((prevCount) => prevCount - 1);
      }, 1000);
    }

    return () => {
      clearInterval(interval);
    };
  }, [program?.time_left]);

  const duration = moment.duration(count, 'seconds')

  const countdownClass = {
    'text-white': true,
    'bg-[#312782]': promotion.type.value === 'bundling',
    'bg-[#329E44]': promotion.type.value === 'discount_loading',
    'bg-[#FAD147]': promotion.type.value === 'merchandise',
    'text-gray-700': promotion.type.value === 'merchandise',
  }

  return (
    <Skeleton isLoaded={query.isFetched} className={clsxm(style.countdownSection, countdownClass)}>
      <span>
        <ClockIcon size={20} />
      </span>
      <span>Berakhir dalam</span>
      <div className={style.countdown}>
        <span>{duration.hours().toString().padStart(2, '0')}</span>
        <span>{duration.minutes().toString().padStart(2, '0')}</span>
        <span>{duration.seconds().toString().padStart(2, '0')}</span>
      </div>
    </Skeleton>
  )
}

export default ProductPromoCardCountdown