import { useCallback, useEffect, useRef } from 'react';

export const useInterval = (callback, delay) => {
  const savedCallback = useRef(callback);
  const intervalIdRef = useRef(undefined);

  useEffect(() => {
    savedCallback.current = callback;
  }, [callback]);

  useEffect(() => {
    const tick = () => {
      savedCallback.current();
    };

    if (delay !== null) {
      intervalIdRef.current = setInterval(tick, delay);
    }

    return () => {
      clearInterval(intervalIdRef.current);
    };
  }, [delay]);

  useEffect(() => {
    const id = intervalIdRef.current;
    return () => {
      clearInterval(id);
    };
  }, []);

  const resetInterval = useCallback(() => {
    clearInterval(intervalIdRef.current);
    intervalIdRef.current = setInterval(savedCallback.current, delay);
  }, [delay]);

  const stopInterval = useCallback(() => {
    clearInterval(intervalIdRef.current);
  }, [delay]);

  return { resetInterval, stopInterval };
};

export default useInterval;
