// src/store/MessageBoxSlice.js
import { createSlice } from "@reduxjs/toolkit";
import { LOCAL_STORAGE } from "../constants/index";

const loadFromLocalStorage = () => {
  try {
    const serializedState = localStorage.getItem(LOCAL_STORAGE.USE_CONFIRM_BOX);
    if (serializedState === null) {
      return true; // Default state if not found in local storage
    }
    return JSON.parse(serializedState);
  } catch (e) {
    console.error("Could not load state from local storage", e);
    return false;
  }
};

const saveToLocalStorage = (state) => {
  try {
    const serializedState = JSON.stringify(state);
    localStorage.setItem(LOCAL_STORAGE.USE_CONFIRM_BOX, serializedState);
  } catch (e) {
    console.error("Could not save state to local storage", e);
  }
};

const clearLocalStorage = () => {
  try {
    localStorage.removeItem(LOCAL_STORAGE.USE_CONFIRM_BOX);
  } catch (e) {
    console.error("Could not clear state from local storage", e);
  }
};

const generalSettingSlice = createSlice({
  name: "generalSetting",
  initialState: {
    useConfirmBox: loadFromLocalStorage(),
  },
  reducers: {
    toggleConfirmBox: (state, action) => {
      state.useConfirmBox = action.payload;
      saveToLocalStorage(state.useConfirmBox);
    },
    resetConfirmBox: (state) => {
      state.useConfirmBox = false;
      clearLocalStorage();
    },
  },
});

export const { toggleConfirmBox, resetConfirmBox } =
  generalSettingSlice.actions;
export default generalSettingSlice.reducer;
