import { Dispatch, SetStateAction, useEffect, useState } from 'react';

type TimeLeftType = number;
type UseTimerReturnType = {
  timeLeft: TimeLeftType;
  setTimeLeft: Dispatch<SetStateAction<TimeLeftType>>;
  resetTimeLeft: () => void;
};

export function useTimer(defaultTimeLeft: TimeLeftType): UseTimerReturnType {
  const [timeLeft, setTimeLeft] = useState<TimeLeftType>(defaultTimeLeft);

  useEffect(() => {
    const timerId = !!timeLeft && setInterval(tick, 1000);
    return () => {
      if (timerId) clearInterval(timerId);
    };
  }, [!!timeLeft]);

  function tick() {
    !!timeLeft && setTimeLeft(timeLeft => timeLeft - 1);
  }

  function resetTimeLeft() {
    setTimeLeft(defaultTimeLeft);
  }

  return { timeLeft, setTimeLeft, resetTimeLeft };
}
