import { create } from 'zustand';
import { devtools } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import { createSelectors } from './createSelectors';

interface Preference {
  navCollapsed: boolean;
  searchCollapsed: boolean;
  notifCenterCollapsed: boolean;
}

type PreferenceState = Preference & {
  updatePreference: (preference: Partial<Preference>) => void;
  resetPreference: (key: keyof Preference) => void;
  togglePreference: (key: keyof Preference) => void;
};

const usePreferenceStoreBase = create<PreferenceState>()(
  devtools(
    immer((set) => ({
      navCollapsed: true,
      searchCollapsed: false,
      notifCenterCollapsed: true,
      updatePreference: (preference) =>
        set((state) => {
          Object.assign(state, preference);
        }),
      resetPreference: (key) =>
        set((state) => {
          state[key] = false;
        }),
      togglePreference: (key) =>
        set((state) => {
          state[key] = !state[key];
        }),
    })),
    {
      name: 'preference-storage',
    },
  ),
);

export const usePreferenceStore = createSelectors(usePreferenceStoreBase);
