import { useEffect, useState } from 'react';

/**
 * Custom hook for managing search input state with focus-aware syncing
 *
 * This hook maintains a local search text state that stays in sync with an external
 * search text value, but only updates when the input is not focused. This prevents
 * the cursor position from jumping while the user is actively typing.
 *
 * @param searchText - The external search text value to sync with
 * @returns Object containing local state, handlers, and props for the input
 *
 * @example
 * const { localSearchText, setLocalSearchText, searchInputProps } = useSearchInput(searchText);
 *
 * <SearchInput
 *   {...searchInputProps}
 *   value={localSearchText}
 *   onChange={(e) => {
 *     setLocalSearchText(e.target.value);
 *     debouncedSearch(e.target.value);
 *   }}
 * />
 */
export function useSearchInput(searchText: string) {
  const [searchInputFocused, setSearchInputFocused] = useState(false);
  const [localSearchText, setLocalSearchText] = useState(searchText);

  // Sync local state with external state when input is not focused
  useEffect(() => {
    if (!searchInputFocused) {
      setLocalSearchText(searchText);
    }
  }, [searchInputFocused, searchText]);

  const searchInputProps = {
    onFocus: () => setSearchInputFocused(true),
    onBlur: () => setSearchInputFocused(false),
  };

  return {
    localSearchText,
    setLocalSearchText,
    searchInputProps,
    searchInputFocused,
  };
}
