import React, { useEffect, useState } from 'react';
import Timer from './index';

export const useCountdownTimer = ({
  initialTimeMs,
  onExpire,
}: {
  initialTimeMs: number;
  onExpire?: () => void;
}) => {
  const countdown = true;
  const [currentTime, setCurrentTime] = useState(initialTimeMs);

  useEffect(() => {
    const timer = setTimeout(() => {
      if (!countingDownAndTimerAtZero(countdown, currentTime))
        setCurrentTime(countdown ? currentTime - 1000 : currentTime + 1000);
    }, 1000);
    return () => clearTimeout(timer);
  });

  useEffect(() => {
    if (currentTime === 0) {
      if (onExpire) {
        onExpire();
      }
    }
  }, [currentTime]);

  return { CountdownTimer: <Timer currentTime={currentTime} />, currentTime };
};

const countingDownAndTimerAtZero = (countdown: boolean, currentTime: number) =>
  countdown && currentTime === 0;
