import { useEffect, useState, useRef } from 'react';
 
function useCountdown(start, interval = 1000) {
  const [count, setCount] = useState(start);
  const [isRunning, setIsRunning] = useState(false);
  const savedCallback = useRef();
 
  // Function to update the count
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const tick = () => {
    setCount((prevCount) => {
      if (prevCount > 1) {
        return prevCount - 1;
      } 
        return start; // Restart countdown
      
    });
  };
 
  // Save the tick function to the ref
  useEffect(() => {
    savedCallback.current = tick;
  }, [tick]);
 
  // Set up the interval using the saved callback
  useEffect(() => {
    if (isRunning) {
      const id = setInterval(() => savedCallback.current(), interval);
      return () => clearInterval(id);
    }
  }, [isRunning, interval]);
 
  const startCountdown = () => setIsRunning(true);
  const stopCountdown = () => setIsRunning(false);
  const resetCountdown = () => {
    setCount(start);
    setIsRunning(false);
  };
 
  return { count, isRunning, startCountdown, stopCountdown, resetCountdown };
}
 
export default useCountdown;
