import React from "react";

export default function useDebounce<T extends (...args: any[]) => void>(
	callback: T,
	delay: number,
) {
	const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);

	const debouncedFunction = React.useCallback(
		(...args: Parameters<T>) => {
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
			}
			timeoutRef.current = setTimeout(() => {
				callback(...args);
			}, delay);
		},
		[callback, delay],
	);

	// Cleanup on unmount
	React.useEffect(() => {
		return () => {
			if (timeoutRef.current) {
				clearTimeout(timeoutRef.current);
			}
		};
	}, []);

	return debouncedFunction;
}
