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

const initialState = {
  panels: [],
  lastPanelAction: "", //"", "push", "pop", "update", "reset", "previewPush", "previewPop", "previewUpdate"
};

// 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 || action.duplicatable) {
          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]);
        }
      });

      let lastAction = 'push';
      if(action.payload.name === panel_names.PLAYER_PANEL){
        if(action.payload.panelInfo.modal){
          lastAction = 'previewPush';
        }
      }
      return {
        ...state,
        panels: newState,
        lastPanelAction: lastAction
      };
    }

    case types.POP_PANEL:{
      let lastAction = 'pop';
      if (action.payload) {
        if(state.lastPanelAction.indexOf('preview')=== 0 && action.payload === panel_names.PLAYER_PANEL){
          lastAction = 'previewPop';
        }
        return {
          ...state,
          panels: state.panels.filter((panel) => panel.name !== action.payload),
          lastPanelAction: lastAction
        };
      } else {
        if(state.lastPanelAction.indexOf('preview')===0){
          lastAction = 'previewPop';
        }
        return {
          ...state,
          panels: state.panels.slice(0, state.panels.length - 1),
          lastPanelAction: lastAction
        };
      }
    }
    case types.UPDATE_PANEL:
    {
      let lastIndex = -1;
      let lastAction = 'update';
      // 배열의 끝에서부터 시작하여 조건에 맞는 마지막 인덱스 찾기
      for (let i = state.panels.length - 1; i >= 0; i--) {
        if (state.panels[i].name === action.payload.name) {
          lastIndex = i;
          break; // 조건에 맞는 첫 번째 요소를 찾으면 루프 종료
        }
      }
      const newPanels = state.panels.map((panel, index) =>
        index === lastIndex
          ? {
              ...panel,
              panelInfo: { ...panel.panelInfo, ...action.payload.panelInfo },
            }
          : panel
      );
      if(newPanels.length > 0){
        const lastPanel = newPanels[newPanels.length-1];
        if(lastPanel.name === panel_names.PLAYER_PANEL && lastPanel.panelInfo.modal){
          lastAction = 'previewUpdate';
        }
      }
      return {
        ...state,
        panels: newPanels,
        lastPanelAction: lastAction
      };
    }
    case types.RESET_PANELS: {
      const updatedPanels = action.payload
        ? action.payload.map((panel) => ({
            ...panel,
            panelInfo: panel.panelInfo || {},
          }))
        : [];

      return {
        ...state,
        panels: updatedPanels,
        lastPanelAction: "reset",
      };
    }

    default:
      return state;
  }
};
