import type { AlertColor, SnackbarOrigin } from '@mui/material';
import { createSlice } from '@reduxjs/toolkit';

import { TYPE_INFO } from '@/modules/@common/notify/constants';

export type SnackBarMessageType = {
  key: string;
  message: string;
  duration?: number;
  variant: AlertColor;
  onClose?: () => void;
  dismissed?: boolean;
  position?: SnackbarOrigin;
};

type NotificationType = {
  key: string;
  dismissed: boolean;
};

type stateType = {
  notifications: NotificationType[];
};

const initialState: stateType = {
  notifications: [],
};

/** https://immerjs.github.io/immer/update-patterns/ */
export const slice = createSlice({
  name: '@@SNACKBAR',
  initialState,
  reducers: {
    notifyAction: (state, action) => {
      state.notifications.push({
        ...action.payload,
        key: `${action.payload.key ?? Math.random().toString(36).slice(2)}`,
        // todo: action.payload.type is the backward compatible property
        variant: action.payload.variant ?? action.payload.type ?? TYPE_INFO,
        dismissed: false,
      });
    },
    closeNotifyAction: (state, action) => {
      const stringKey = `${action.payload}`;

      state.notifications.forEach((notification) => {
        // eslint-disable-next-line no-param-reassign
        notification.dismissed = !action.payload || notification.key === stringKey;
      });
    },
    removeSnackbarAction: (state, action) => {
      const stringKey = `${action.payload}`;

      const index = state.notifications.findIndex((notification) => notification.key === stringKey);

      if (index !== -1) {
        state.notifications.splice(index, 1);
      }
    },
  },
});

export const { notifyAction, closeNotifyAction, removeSnackbarAction } = slice.actions;

export default slice.reducer;
