import { useCallback } from 'react';

import { createStore, useStore } from '../use-store';
import { isBrowser } from '../../utils/js-utils';

const RECENT_SEARCHES_KEY = 'recentSearches';
const RECENT_SEARCHES_LIMIT = 5;

const recentSearchesStore = createStore<string[]>({
  storageKey: RECENT_SEARCHES_KEY,
});

export const useRecentSearches = (): {
  items: string[];
  addSearchHistoryItem: (value: string) => void;
  removeSearchHistoryItem: (value: string) => void;
} => {
  const [items, setItems] = useStore<string[]>(recentSearchesStore, []);

  const updateItems = useCallback(
    (value: string, isAdd: boolean) => {
      if (!isBrowser()) return;

      const currentItems = [...items];
      const valueIndex = currentItems.indexOf(value);
      if (valueIndex !== -1) {
        currentItems.splice(valueIndex, 1);
      }

      if (isAdd) {
        currentItems.unshift(value);
      }

      const limitedItems = currentItems.slice(0, RECENT_SEARCHES_LIMIT);

      setItems(limitedItems);
    },
    [items, setItems],
  );

  const addSearchHistoryItem = useCallback(
    (value: string) => {
      updateItems(value, true);
    },
    [updateItems],
  );

  const removeSearchHistoryItem = useCallback(
    (value: string) => {
      updateItems(value, false);
    },
    [updateItems],
  );

  return { items, addSearchHistoryItem, removeSearchHistoryItem };
};
