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

import { PROVIDER_VALUE_GOOGLE } from '../../../List/constants';
import { REDUX_ATTRIBUTE_FORM_FIELD_NAME, REDUX_FIELD_NAME, TAB_GENERAL } from '../../constants';

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

const formSlice = createFormSlice(REDUX_FIELD_NAME, validationScheme);
const formAttributeSlice = createFormSlice(REDUX_ATTRIBUTE_FORM_FIELD_NAME, validationAttributesScheme);

export const { validateFields, validateSingleField } = formSlice;
export const { validateFields: validateAttributeFields } = formAttributeSlice;

const initialState = {
  id: null,
  displayName: '',
  allDomains: false,
  onlyExisting: true,
  domains: [''],
  metadataURL: '',
  ssoDefaultHubs: [],
  hubOptions: null,
  allHubs: false,
  ssoCustomAttributes: [],
  provider: PROVIDER_VALUE_GOOGLE,
  settings: {
    allDomainsDisabled: false,
    cannotCreateProfile: false,
    singleSignOnUrl: '',
    audienceUri: '',
  },

  // attributes form
  attributeName: '',
  attributesKeyValues: [['', '']],
  attributeHubs: [],
  attributeAllHubs: false,

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
  ...formAttributeSlice.state,
};

export const slice = createSlice({
  name: '@@SSO/EDITOR',
  initialState,
  reducers: {
    setAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setInitialAction: () => ({
      ...initialState,
    }),
    setAttributesFormToInitialAction: (state) => {
      state.attributeName = '';
      state.attributesKeyValues = [['', '']];
      state.attributeHubs = [];
    },
    getItemAction: (state) => state,
    getHubOptionsAction: (state) => state,
    createItemAction: (state) => state,
    updateItemAction: (state) => state,

    setScrollToFieldNameAction: formSlice.actions.setScrollToFieldAction,
    setErrorByPropAction: formSlice.actions.updateValidationSchemeAction,
    removeErrorByPropAction: formSlice.actions.removeErrorByFieldNameAction,

    setScrollToFieldNameAttributeFormAction: formAttributeSlice.actions.setScrollToFieldAction,
    setErrorByPropAttributeFormAction: formAttributeSlice.actions.updateValidationSchemeAction,
    removeErrorByPropAttributeFormAction: formAttributeSlice.actions.removeErrorByFieldNameAction,
  },
});

export const {
  setAction,
  setInitialAction,
  getItemAction,
  getHubOptionsAction,
  createItemAction,
  updateItemAction,
  setAttributesFormToInitialAction,

  removeErrorByPropAction,
  setErrorByPropAction,
  setScrollToFieldNameAction,

  setScrollToFieldNameAttributeFormAction,
  setErrorByPropAttributeFormAction,
  removeErrorByPropAttributeFormAction,
} = slice.actions;

export default slice.reducer;
