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

import { STATUSES_ACTIVE, STATUSES_INACTIVE } from '../../../List/constants';
import { REDUX_FIELD_NAME, TAB_GENERAL } from '../../constants';

import { validationScheme } from '../../helpers/validationScheme';
import createFormSlice from '@/modules/@common/Form/redux/slices';

const formSlice = createFormSlice(REDUX_FIELD_NAME, validationScheme);

export const { validateFields, validateSingleField } = formSlice;

const initialState = {
  id: null,
  email: '',
  firstName: '',
  lastName: '',
  status: STATUSES_ACTIVE,
  enable2fa: false,
  sendInvite: true,
  allSites: false,

  updateDate: '',
  updatedBy: '',

  timezone: null,
  timezoneOptions: null,

  role: null,
  roleOptions: null,

  defaultHub: null,
  publisherIds: [],

  department: null,
  departmentOptions: null,

  account: null,
  accountOptions: null,

  contentOwner: null,
  contentOwnersOptions: null,

  initialRoleName: null,
  initialRoleType: null,
  initialEmail: null,
  initialStatus: STATUSES_INACTIVE,

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@USERS/EDITOR',
  initialState,
  reducers: {
    setAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setInitialAction: () => ({
      ...initialState,
    }),
    impersonateUserAction: (state) => state,
    getItemAction: (state) => state,
    getAccountOptionsAction: (state) => state,
    getContentOwnersOptionsAction: (state) => state,
    getDemandAccountsOptionsAction: (state) => state,
    getTemplatePlayerOptionsAction: (state) => state,
    createDepartmentAction: (state) => state,
    createItemAction: (state) => state,
    updateItemAction: (state) => state,
    getRoleOptionsAction: (state) => state,
    getTimezoneOptionsAction: (state) => state,
    getDepartmentOptionsAction: (state) => state,

    setActiveTabIdAction: (state, action) => {
      state.activeTabId = action.payload;
    },

    setScrollToFieldNameAction: formSlice.actions.setScrollToFieldAction,
    setErrorByPropAction: formSlice.actions.updateValidationSchemeAction,
    removeErrorByPropAction: formSlice.actions.removeErrorByFieldNameAction,
  },
});

export const {
  setAction,
  setInitialAction,
  getItemAction,
  impersonateUserAction,
  getAccountOptionsAction,
  getContentOwnersOptionsAction,
  createItemAction,
  updateItemAction,
  createDepartmentAction,
  getRoleOptionsAction,
  getTimezoneOptionsAction,
  getDepartmentOptionsAction,

  setActiveTabIdAction,
  removeErrorByPropAction,
  setErrorByPropAction,
  setScrollToFieldNameAction,
} = slice.actions;

export default slice.reducer;
