import { useState, useEffect } from 'react';

const BASE = 10;

function useCountdownTimer(
  initialMinutes = 0,
  initialSeconds = 0,
  onTimerFinished?: () => void,
) {
  const [time, setTime] = useState([initialMinutes, initialSeconds]);
  const [isActive, setIsActive] = useState(false);
  const [mins, secs] = time;

  const formatTime = (minutes, seconds) => {
    return `${minutes < BASE ? '0' : ''}${minutes}:${seconds < BASE ? '0' : ''}${seconds}`;
  };

  const start = () => {
    setIsActive(true);
  };

  const pause = () => {
    setIsActive(false);
  };

  const reset = () => {
    setIsActive(false);
    setTime([initialMinutes, initialSeconds]);
  };

  useEffect(() => {
    let interval;
    if (isActive) {
      interval = setInterval(() => {
        setTime(([m, s]) => {
          if (s === 0 && m === 0) {
            clearInterval(interval);
            onTimerFinished && onTimerFinished();
            pause();
            return [0, 0];
          } else if (s === 0) {
            return [m - 1, 59];
          } else {
            return [m, s - 1];
          }
        });
      }, 1000);
    }

    return () => clearInterval(interval);
  }, [isActive, time]);

  return { timer: formatTime(mins, secs), start, pause, reset };
}

export default useCountdownTimer;
