import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { LAYER_IDS } from "../Map/Layers/constants";
import { persist } from "zustand/middleware";

const INITIAL_STATE = {
  [LAYER_IDS.initial]: true,
  [LAYER_IDS.approve]: true,
  [LAYER_IDS.working]: true,
  [LAYER_IDS.filteredWorking]: false,
  [LAYER_IDS.cancelled]: true,
  [LAYER_IDS.pvz]: true,
  [LAYER_IDS.other]: true,
};

const STATIC_LAYERS = [LAYER_IDS.pvz, LAYER_IDS.other];

const store = (set) => ({
  isVisible: INITIAL_STATE,

  toggleVisibility: (layerId) =>
    set((state) => {
      state.isVisible[layerId] = !state.isVisible[layerId];
    }),

  showLayers: (layerIds) =>
    set((state) => {
      layerIds.forEach((layerId) => {
        state.isVisible[layerId] = true;
      });
    }),

  setLayersVisibility: (visibleLayerIds) =>
    set((state) => {
      visibleLayerIds.forEach((layerId) => {
        state.isVisible[layerId] = true;
      });
      const invisibleLayersIds = Object.keys(state.isVisible).filter(
        (l) => !visibleLayerIds.includes(l) && !STATIC_LAYERS.includes(l)
      );
      invisibleLayersIds.forEach((layerId) => {
        state.isVisible[layerId] = false;
      });
    }),
});

export const useLayersVisibility = create(
  persist(immer(store), { name: "postnet/layers-visibility" })
);
