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

import { TYPE_INTERNAL } from '../../../List/constants';
import { DEFAULT_PAGE_VIDEO_MANAGER, REDUX_FIELD_NAME, TAB_DETAILS } 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 = {
  displayName: '',
  type: TYPE_INTERNAL,
  account: null,
  accountOptions: null,
  defaultPage: DEFAULT_PAGE_VIDEO_MANAGER,
  visibleInSelfServe: false,
  readOnlyInSelfServe: true,
  permissions: {}, // applied permissions
  permissionsModules: [], // permissions list for build UI

  activeTabId: TAB_DETAILS,

  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@ROLES_PERMISSIONS/EDITOR',
  initialState,
  reducers: {
    setAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setInitialAction: () => ({
      ...initialState,
    }),
    getItemAction: (state) => state,
    getAccountOptionsAction: (state) => state,
    createItemAction: (state) => state,
    updateItemAction: (state) => state,
    updateRoleModuleMetadataAction: (state) => state,
    updatePermissionsMetadataAction: (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,
  getAccountOptionsAction,
  createItemAction,
  updateItemAction,
  updateRoleModuleMetadataAction,
  updatePermissionsMetadataAction,

  setActiveTabIdAction,

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

export default slice.reducer;
