import { useState, useRef, useCallback, useId, useEffect } from 'react';
import useSearchResults from './useSearchResults';
const useSearchEvents = function useSearchEvents({
  searchOptions,
  searchKey,
  customSearch,
  setValue,
  value
}) {
  // Tracking current user input
  const [searchQuery, setSearchQuery] = useState('');
  // Tracking active descendent in results list
  const [activeDescendent, setActiveDescendent] = useState(-1);
  // Track whether popup should be visible
  const [showList, setShowList] = useState(false);
  const inputRef = useRef();
  const resultsId = useId();
  const inputId = useId();
  const searchResults = useSearchResults({
    query: searchQuery,
    searchKey,
    options: searchOptions,
    customSearch
  });
  const updateActiveDescendent = useCallback(({
    direction,
    type
  }) => {
    if (type === 'reset') {
      setActiveDescendent(-1);
      return;
    }
    if (direction === 'down') {
      setActiveDescendent(prev => {
        if (prev > searchResults.results.length - 1) {
          return 0;
        }
        return prev + 1;
      });
      return;
    }
    if (direction === 'up') {
      setActiveDescendent(prev => {
        if (prev === 0) {
          return searchResults.results.length - 1;
        }
        return prev - 1;
      });
    }
  }, [setActiveDescendent, searchResults]);
  const closeResults = () => {
    setSearchQuery('');
    updateActiveDescendent({
      type: 'reset'
    });
    setShowList(false);
  };
  const updateUserSelection = useCallback(result => {
    const inferredResult = result || searchResults.results[activeDescendent];
    closeResults();
    setValue(inferredResult);
  }, [searchResults, inputRef, setValue, activeDescendent]);
  useEffect(() => {
    // Make sure we scroll visually focused element into view
    const elId = `${resultsId}-${activeDescendent}`;
    if (activeDescendent === -1) {
      return;
    }
    const el = window.document.getElementById(elId);
    if (!el) return;
    el.scrollIntoView({
      block: 'end'
    });
  }, [resultsId, activeDescendent]);
  useEffect(() => {
    // set value of input to result just once
    inputRef.current.value = value && value[searchKey] ? value[searchKey] : '';
  }, [value]);
  return {
    searchQuery,
    setSearchQuery,
    searchResults,
    closeResults,
    activeDescendent,
    updateActiveDescendent,
    updateUserSelection,
    inputRef,
    resultsId,
    inputId,
    showList,
    setShowList
  };
};
export default useSearchEvents;