import { createSlice } from "@reduxjs/toolkit";

export const miniwindowConfig = {
  status: false,
  component: null,
  data: {},
  results: null,
  callback: null,
};

export const miniwindowSlice = createSlice({
  name: "miniwindow",
  initialState: {
    miniwindow: [],
  },
  reducers: {
    addMiniWindow: (state, action) => {
      state.miniwindow = [...state.miniwindow, action.payload];
    },

    hideMiniWindowOnIndex: (state, action) => {
      state.miniwindow = state.miniwindow.map((item, index) =>
        index === action.payload ? { ...item, status: false } : item
      );

      const isHideAllModal = state.miniwindow.every((item) => !item.status);
      if (isHideAllModal) state.miniwindow = [];
    },

    hideMiniWindowBy: (state, action) => {
      const { role, value } = action.payload;
      state.miniwindow = state.miniwindow.map((item) =>
        item[role] !== value ? item : { ...item, status: false }
      );
    },

    removeAllMiniWindow: (state) => {
      state.miniwindow = [];
    },
  },
  selectors: {
    selectMiniWindow: (state) => state.miniwindow,
  },
});

export const {
  addMiniWindow,
  hideMiniWindowOnIndex,
  removeAllMiniWindow,
  hideMiniWindowBy,
} = miniwindowSlice.actions;
export const { selectMiniWindow } = miniwindowSlice.selectors;

export default miniwindowSlice.reducer;
