import {createSlice} from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit';

import {
  PREFERENCES_VARS,
  preferences_vars_default,
  RegisterProcess,
  ThemeMode,
} from './appVar';
import {non_save_vars, NON_SAVE_VARS} from './appNonSaveVar';
import LangFormat from '@caj/lang/default';
import {lang as defaultLang} from '@caj/lang/en';
import {UserId} from './types';
import {MyUserAccount} from '@caj/user/types';

export interface appVariablesState {
  preferences: PREFERENCES_VARS;
  lang: LangFormat;
}

const initialState: appVariablesState = {
  preferences: preferences_vars_default,
  lang: defaultLang,
};

export const appVariablesSlice = createSlice({
  name: 'appVariables',
  initialState,
  reducers: {
    setTheme: (state, action: PayloadAction<ThemeMode>) => {
      state.preferences.theme = action.payload;
    },
    setLang: (state, action: PayloadAction<LangFormat>) => {
      state.lang = action.payload;
    },
    loadPreferences: (state, action: PayloadAction<PREFERENCES_VARS>) => {
      state.preferences = action.payload;
    },
    setRegisterProcess: (state, action: PayloadAction<RegisterProcess>) => {
      state.preferences.RegisterProcess = action.payload;
    },
    setCurrentAccount: (state, action: PayloadAction<UserId>) => {
      state.preferences.selectedAccount = action.payload;
    },
    setAccount: (state, action: PayloadAction<MyUserAccount>) => {
      state.preferences.accounts[action.payload.UserId] = action.payload;
    },
    setDBEK: (state, action: PayloadAction<number>) => {
      state.preferences.dbek = action.payload;
    },
  },
});

// Action creators are generated for each case reducer function
const {actions} = appVariablesSlice;
export const appVarActions = actions;

export default appVariablesSlice.reducer;
