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

function useDelayedLoading(loading: boolean, delay: number = 300) {
  const [showLoading, setShowLoading] = useState(false);
  const delayTimeout = useRef<NodeJS.Timeout | null>(null);

  useEffect(() => {
    if (delayTimeout.current) {
      clearTimeout(delayTimeout.current);
    }
    if (loading) {
      delayTimeout.current = setTimeout(() => {
        setShowLoading(true);
      }, delay);
    } else {
      setShowLoading(false);
    }
    return () => {
      if (delayTimeout.current) {
        clearTimeout(delayTimeout.current);
      }
    };
  }, [loading, delay]);

  return showLoading;
}

export default useDelayedLoading;
