import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { SnackbarLevel } from "components/snackbar";
import { UIState } from "./state";
import { DEFAULT_SNACKBAR_DURATION } from "./constants";

const initialState: UIState = {
  isOpen: false,
  level: "error",
  message: "",
};

export const uiSlice = createSlice({
  name: "ui",
  initialState,
  reducers: {
    openSnackbar: (
      state,
      action: PayloadAction<{
        level: SnackbarLevel;
        message: string;
        duration?: number;
      }>
    ) => {
      const { level, message, duration } = action.payload;
      state.isOpen = true;
      state.level = level;
      state.message = message;
      state.duration =
        level === "error" ? undefined : duration ?? DEFAULT_SNACKBAR_DURATION;
    },
    closeSnackbar: (state) => {
      state.isOpen = false;
    },
  },
});
export const { openSnackbar, closeSnackbar } = uiSlice.actions;

export default uiSlice.reducer;
