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

export const INITIAL = {
  region: null,
  deltaTraffic: [-10000, 10000],
  factTraffic: [-100, 0],
  age: [-1, 0],
};

export const INITIAL_RANGES = {
  region: null,
  deltaTraffic: [-10000, 10000],
  factTraffic: [-100, 0],
  age: [-1, 0],
};

const store = (set) => ({
  filters: INITIAL,
  ranges: INITIAL_RANGES,

  setDeltaTraffic: (value) => {
    set((state) => {
      state.filters.deltaTraffic = value;
    });
  },

  setFactTraffic: (value) => {
    set((state) => {
      state.filters.factTraffic = value;
    });
  },

  setAge: (value) => {
    set((state) => {
      state.filters.age = value;
    });
  },

  setRegion: (value) =>
    set((state) => {
      state.filters.region = value;
    }),

  setRanges: (value) =>
    set((state) => {
      state.ranges = value;
    }),

  clear: (fullRange) =>
    set((state) => {
      if (!fullRange) {
        state.filters = INITIAL;
        return state;
      }

      const { deltaTraffic, factTraffic, age } = fullRange;

      state.filters = {
        ...INITIAL,
        deltaTraffic,
        factTraffic,
        age,
      };
    }),
});

export const useWorkingPointsFilters = create(
  persist(immer(store), { name: "postnet/working-filters" })
);
