import { create } from "zustand";
import { persist } from "zustand/middleware";
import { immer } from "zustand/middleware/immer";

export interface FilterItem {
  id: number;
  name: string;
  type: string;
}

interface FilterZustandTypes {
  filter: FilterItem[];
  removeFilter: (id: number) => void;
  toggleFilter: (item: FilterItem) => void;
  resetFilter: () => void;
  hasFilter: (name: string) => boolean;
  getFiltersByType: (type: string) => FilterItem[]; // ✅ Qo'shimcha
  removeFiltersByType: (type: string) => void; // ✅ Qo'shimcha
}

export const useFilter = create<FilterZustandTypes>()(
  persist(
    immer((set, get) => ({
      filter: [],

      removeFilter: (id) =>
        set((state) => {
          state.filter = state.filter.filter((item:FilterItem) => item.id !== id);
        }),

      toggleFilter: (item) =>
        set((state) => {
          const index = state.filter.findIndex((f:FilterItem) => f.name === item.name);
          if (index !== -1) {
            // Agar bor bo'lsa o'chirish
            state.filter.splice(index, 1);
          } else {
            // Agar yo'q bo'lsa qo'shish
            state.filter.push(item);
          }
        }),

      resetFilter: () =>
        set((state) => {
          state.filter = [];
        }),

      hasFilter: (name) => {
        return get().filter.some((item) => item.name === name);
      },

      // ✅ Type bo'yicha filterlarni olish
      getFiltersByType: (type) => {
        return get().filter.filter((item) => item.type === type);
      },

      // ✅ Type bo'yicha filterlarni o'chirish
      removeFiltersByType: (type) =>
        set((state) => {
          state.filter = state.filter.filter((item:FilterItem) => item.type !== type);
        }),
    })),
    {
      name: "filter-storage", // localStorage key nomi
      partialize: (state) => ({ filter: state.filter }), // Faqat filter'ni saqlash
    }
  )
);