import { useState, useEffect, useRef } from 'react';
import defaultSearch from './search';

/**
 * Hook to debounce search results.
 */
const useSearchResults = function useSearchResults({
  query,
  customSearch,
  searchKey,
  activeDescendent,
  options,
  debounce = 150
}) {
  const search = customSearch || defaultSearch;
  const [results, setResults] = useState(() => search({
    query,
    searchKey,
    options
  }));
  const timer = useRef(null);
  useEffect(() => {
    timer.current = setTimeout(() => {
      timer.current = null;
      setResults(search({
        query,
        searchKey,
        options,
        activeDescendent
      }));
    }, debounce);
    return () => {
      if (timer.current) clearTimeout(timer.current);
    };
  }, [query, options, debounce, activeDescendent]);
  return results;
};
export default useSearchResults;