import { useMemo, useState } from 'react';
import { IProductBlueprint, ItemType } from '@rpg-engine/shared';
import { IOptionsProps } from '../components/Dropdown';

export const useStoreFiltering = (items: IProductBlueprint[]) => {
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<ItemType | 'all'>(
    'all'
  );

  const categoryOptions: IOptionsProps[] = useMemo(() => {
    const uniqueCategories = Array.from(
      new Set(items.map(item => item.itemType))
    );
    const allCategories = ['all', ...uniqueCategories] as (ItemType | 'all')[];
    return allCategories.map((category, index) => ({
      id: index,
      value: category,
      option: category === 'all' ? 'All' : category,
    }));
  }, [items]);

  const filteredItems = useMemo(() => {
    return items
      .filter(item => {
        const matchesSearch = item.name
          .toLowerCase()
          .includes(searchQuery.toLowerCase());
        const matchesCategory =
          selectedCategory === 'all' || item.itemType === selectedCategory;
        return matchesSearch && matchesCategory;
      })
      .sort((a, b) => {
        const aHighlighted = a.store?.isHighlighted || false;
        const bHighlighted = b.store?.isHighlighted || false;

        if (aHighlighted && !bHighlighted) return -1;
        if (!aHighlighted && bHighlighted) return 1;
        return 0;
      });
  }, [items, searchQuery, selectedCategory]);

  return {
    searchQuery,
    setSearchQuery,
    selectedCategory,
    setSelectedCategory,
    categoryOptions,
    filteredItems,
  };
};
