import {debounce} from 'lodash-es';
import {useCallback, useMemo, useState} from 'react';

export function useSelectFilterOptions<
  O extends {label?: string; value?: string},
>(options: O[]) {
  const [search, setSearch] = useState('');

  const onSelectSearch = useMemo(function () {
    return debounce(setSearch, 500, {leading: false, trailing: true});
  }, []);

  const clearSearch = useCallback(function () {
    setSearch('');
  }, []);

  const result = useMemo(
    function () {
      if (!search) return options;

      return options.filter(
        ({label, value}) => label?.includes(search) || value?.includes(search),
      );
    },
    [options, search],
  );

  return [result, {onSelectSearch, clearSearch}] as const;
}
