import { types } from "../actions/actionTypes";
import { panel_names } from "../utils/Config";

const initialState = {
  panels: [],
  isModalOpen: false,
};

// last one will be on top
const forceTopPanels = [
  panel_names.ERROR_PANEL,
  panel_names.INTRO_PANEL,
  panel_names.DEBUG_PANEL,
];

export const panelsReducer = (state = initialState, action) => {
  switch (action.type) {
    case types.PUSH_PANEL: {
      const panelInfo = action.payload.panelInfo || {};
      const forceTopPanelsInfo = [];
      const newState = [];

      state.panels.forEach((panel) => {
        const forceTopIndex = forceTopPanels.indexOf(panel.name);

        if (forceTopIndex >= 0) {
          forceTopPanelsInfo[forceTopIndex] = panel;
        } else if (panel.name !== action.payload.name) {
          newState.push(panel);
        }
      });

      const newPanelForceTopIndex = forceTopPanels.indexOf(action.payload.name);

      if (newPanelForceTopIndex >= 0) {
        forceTopPanelsInfo[newPanelForceTopIndex] = {
          ...action.payload,
          panelInfo,
        };
      } else {
        newState.push({ ...action.payload, panelInfo });
      }

      forceTopPanels.forEach((_, index) => {
        if (forceTopPanelsInfo[index]) {
          newState.push(forceTopPanelsInfo[index]);
        }
      });

      return {
        ...state,
        panels: newState,
      };
    }

    case types.POP_PANEL:
      if (action.payload) {
        return {
          ...state,
          panels: state.panels.filter((panel) => panel.name !== action.payload),
        };
      } else {
        return {
          ...state,
          panels: state.panels.slice(0, state.panels.length - 1),
        };
      }

    case types.UPDATE_PANEL:
      return {
        ...state,
        panels: state.panels.map((panel) =>
          panel.name === action.payload.name
            ? {
                ...panel,
                panelInfo: { ...panel.panelInfo, ...action.payload.panelInfo },
              }
            : panel
        ),
      };

    case types.UPDATE_MODAL_STATUS:
      return {
        ...state,
        isModalOpen: action.payload,
      };

    case types.RESET_PANELS: {
      const updatedPanels = action.payload
        ? action.payload.map((panel) => ({
            ...panel,
            panelInfo: panel.panelInfo || {},
          }))
        : [];

      return {
        ...state,
        panels: updatedPanels,
        isModalOpen: false,
      };
    }

    default:
      return state;
  }
};
