summaryrefslogtreecommitdiff
path: root/src-migrate/modules/product-promo/components/CardCountdown.tsx
blob: b61ad11588621dfc664945e7472e82ef7cd01b29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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