import { useCallback } from 'react';

import useLocalStorage from 'src/hooks/useLocalStorage';

const STORAGE_KEY = 'global-search:recent';
const MAX_RECENT = 5;

export function useRecentSearches() {
  const [recentSearches, setRecentSearches] = useLocalStorage<string[]>(
    STORAGE_KEY,
    [],
  );

  const addRecentSearch = useCallback(
    (term: string) => {
      const trimmed = term.trim();
      if (!trimmed) {
        return;
      }

      setRecentSearches(prev => {
        const withoutDuplicate = prev.filter(
          item => item.toLowerCase() !== trimmed.toLowerCase(),
        );
        return [trimmed, ...withoutDuplicate].slice(0, MAX_RECENT);
      });
    },
    [setRecentSearches],
  );

  const removeRecentSearch = useCallback(
    (term: string) => {
      setRecentSearches(prev =>
        prev.filter(item => item.toLowerCase() !== term.toLowerCase()),
      );
    },
    [setRecentSearches],
  );

  const clearRecentSearches = useCallback(() => {
    setRecentSearches([]);
  }, [setRecentSearches]);

  return {
    recentSearches,
    addRecentSearch,
    removeRecentSearch,
    clearRecentSearches,
  };
}
