// Note: This is a copy of the useDebounce from material-hu with the isDeboungcing state
import { useState, useEffect } from 'react';

const useDebounce = <T>(value: T, delay: number = 500) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  const [isDebouncing, setIsDebouncing] = useState(false);

  useEffect(() => {
    setIsDebouncing(true);
    const handler = setTimeout(() => {
      setIsDebouncing(false);
      setDebouncedValue(value);
    }, delay);

    // Cancel the timeout if value changes (also on delay change or unmount)
    return () => {
      setIsDebouncing(false);
      clearTimeout(handler);
    };
  }, [JSON.stringify(value), delay]);

  return { debouncedValue, isDebouncing };
};

export { useDebounce };
