import { useEffect, useState } from '@tarojs/taro';

const useCountDown = (countDownTime: number) => {
  const [count, setCount] = useState(countDownTime);
  let timer: NodeJS.Timeout | null = null;

  useEffect(() => {
    timer && clearInterval(timer);
    if (countDownTime) {
      setCount(countDownTime);
    }
  }, [countDownTime]);

  useEffect(() => {
    timer = setTimeout(() => {
      // console.log(countDownTime, count);
      let newCount = count - 1;
      if (newCount < 0) {
        timer && clearInterval(timer);
        return;
      }
      setCount(newCount);
    }, 1000);

    return () => {
      timer && clearInterval(timer);
    };
  }, [count]);

  return count;
};

export default useCountDown;
