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

export const INITIAL = {
  region: null,
  prob1__gt: 0,
  prob1__lt: 5000,
  prob2__gt: 0,
  prob2__lt: 5000,
  prob3__gt: 0,
  prob3__lt: 5000,
  prob4__gt: 0,
  prob4__lt: 5000,
  prob5__gt: 0,
  prob5__lt: 5000,
  prob6__gt: 0,
  prob6__lt: 5000,
  cooling_time__gt: 0,
  cooling_time__lt: 5000,
  priority__gt: 0,
  priority__lt: 5000,
};

const INITIAL_RANGES = {
  prob1: [0, 5000],
  prob2: [0, 5000],
  prob3: [0, 5000],
  prob4: [0, 5000],
  prob5: [0, 5000],
  prob6: [0, 5000],
  cooling_time: [0, 5000],
  priority: [0, 5000],
}

const store = (set) => ({
  filters: INITIAL,
  consumer_filter: null,
  consumer_ranges: null,
  source_filter: null,
  consumer_type: null,
  energy_class: null,
  wall_material: null,
  ranges: INITIAL_RANGES,

  setConsumerFilter: (key, value) =>
    set((state) => {
      if (!key) {
        state.consumer_filter = null;
        return;
      }
      const arr = value ? value : state.ranges[key];
      state.consumer_filter = {
        key: key,
        gt: arr[0],
        lt: arr[1],
      };
    }),

  setSourceFilter: (key, value) =>
    set((state) => {
      if (!key) {
        state.source_filter = null;
        return;
      }
      const arr = value ? value : state.ranges[key];
      state.source_filter = {
        key: key,
        gt: arr[0],
        lt: arr[1],
      };
    }),

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

  setConsumerType: (value) =>
    set((state) => {
      state.consumer_type = value;
    }),

  setEnergyClass: (value) =>
    set((state) => {
      state.energy_class = value;
    }),

  setWallMaterial: (value) =>
    set((state) => {
      state.wall_material = value;
    }),

  setFilterWithKey: (value, key) =>
    set((state) => {
      state.filters[`${key}__gt`] = value[0];
      state.filters[`${key}__lt`] = value[1];
    }),

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

  clear: (fullRange) =>
    set((state) => {

      state.consumer_filter = null;
      state.source_filter = null;
      state.energy_class = null;
      state.consumer_type = null;
      state.wall_material = null;
      if (!fullRange) {
        state.filters = INITIAL;
        return state;
      }
      state.filters = {
        ...INITIAL,
        prediction: fullRange.prediction,
      };
    }),
});

export const useDzkhFilters = create(
  persist(immer(store), { name: "dzkh/filters" })
);
