import { useLocation } from 'react-router-dom';

import { useQueryState } from 'nuqs';
import { useDebounce } from '@material-hu/hooks/useDebounce';

import { isSearchValid } from '../utils';

export const useSidebarSearchQuery = () => {
  const [search, setSearch] = useQueryState('search', { defaultValue: '' });
  const debouncedSearch = useDebounce(search);
  const { search: locationSearch } = useLocation();

  const urlSearch = new URLSearchParams(locationSearch).get('search') ?? '';
  const hasSearch = isSearchValid(search) || isSearchValid(urlSearch);

  const isSearchPending = search !== debouncedSearch;

  return { search, setSearch, debouncedSearch, hasSearch, isSearchPending };
};
