import { useCallback, useEffect, useRef, useState } from "react";

export default function useCountdownTimer() {
  const [timer, setTimer] = useState(0);
  const ref = useRef(null);

  const stop = useCallback(() => {
    if (ref.current) clearInterval(ref.current);
    ref.current = null;
  }, []);

  const start = useCallback(
    (seconds = 120) => {
      stop();
      setTimer(seconds);
      ref.current = setInterval(() => {
        setTimer((t) => {
          if (t <= 1) {
            stop();
            return 0;
          }
          return t - 1;
        });
      }, 1000);
    },
    [stop]
  );

  const reset = useCallback(() => {
    stop();
    setTimer(0);
  }, [stop]);

  useEffect(() => () => stop(), [stop]);

  return { timer, start, stop, reset, setTimer };
}
