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

// Taken and adapted from:
// https://www.joshwcomeau.com/snippets/react-hooks/use-random-interval/

const random = (min: number, max: number) =>
	Math.floor(Math.random() * (max - min)) + min;

export default function useRandomInterval(
	callback: () => void,
	minDelay: number | null,
	maxDelay: number | null,
) {
	const timeoutId = useRef<number | null>(null);
	const savedCallback = useRef(callback);

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

	useEffect(() => {
		const isEnabled =
			typeof minDelay === "number" && typeof maxDelay === "number";
		if (isEnabled) {
			const handleTick = () => {
				const nextTickAt = random(minDelay, maxDelay);
				timeoutId.current = window.setTimeout(() => {
					savedCallback.current();
					handleTick();
				}, nextTickAt);
			};
			handleTick();
		}

		return () => {
			if (typeof timeoutId.current === "number") {
				window.clearTimeout(timeoutId.current);
			}
		};
	}, [minDelay, maxDelay]);

	const cancel = useCallback(() => {
		if (typeof timeoutId.current === "number") {
			window.clearTimeout(timeoutId.current);
		}
	}, []);

	return cancel;
}
