import { create } from 'zustand';
import { createJSONStorage, devtools, persist } from 'zustand/middleware';
import { TableFilterStore } from '@/types/stores';

type TableFilterStoreState = TableFilterStore<
  Record<string, Record<string, unknown>>
>;

export const useTableFilterStore = create<TableFilterStoreState>()(
  devtools(
    persist(
      (set) => ({
        data: {},

        setData: (newData) => {
          set({ data: newData });
        },

        setTableData: (key, tableData) => {
          set((state) => ({
            data: {
              ...state.data,
              [key]: tableData,
            },
          }));
        },

        setTableDataField: (key, field, value) => {
          set((state) => ({
            data: {
              ...state.data,
              [key]: {
                ...state.data[key],
                [field]: value,
              },
            },
          }));
        },

        setSearchValue: (key, searchValue) => {
          set((state) => ({
            data: {
              ...state.data,
              [key]: {
                ...state.data[key],

                // search key
                search: searchValue,
              },
            },
          }));
        },
      }),
      {
        name: 'table-filter-store',
        storage: createJSONStorage(() => sessionStorage),
      }
    )
  )
);
