export const MODAL_TOGGLE = 'MODAL_TOGGLE';
export const modalToggle = ({ selectedModalId, hasOverlay }) => ({
  type: MODAL_TOGGLE,
  selectedModalId,
  hasOverlay,
});

export const OVERLAY_MODAL_HIDE_ALL = 'OVERLAY_MODAL_HIDE_ALL';
export const overlayModalsHideAll = () => ({
  type: OVERLAY_MODAL_HIDE_ALL,
});

const INITIAL_STATE = {
  activeModalIds: [],
  activeOverlayModalIds: [],
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case MODAL_TOGGLE: {
      const { activeModalIds, activeOverlayModalIds } = state;
      const { selectedModalId, hasOverlay } = action;
      return {
        ...state,
        activeModalIds: !hasOverlay
          ? !activeModalIds.includes(selectedModalId)
            ? [...activeModalIds, selectedModalId]
            : activeModalIds.filter(id => id !== selectedModalId)
          : activeModalIds,
        activeOverlayModalIds: !hasOverlay
          ? activeOverlayModalIds
          : !activeOverlayModalIds.includes(selectedModalId)
            ? [...activeOverlayModalIds, selectedModalId]
            : activeOverlayModalIds.filter(id => id !== selectedModalId),
      };
    }

    case OVERLAY_MODAL_HIDE_ALL: {
      return {
        ...state,
        activeOverlayModalIds: [],
      };
    }

    default:
      return state;
  }
};
