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

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,
  name: '',
  advertiser: null,
  advertiserOptions: null,
  hub: null,
  hubOptions: null,

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

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

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

export const {
  setAction,
  setInitialAction,
  getItemAction,
  getAdvertiserOptionsAction,
  createAdvertiserAction,
  getHubOptionsAction,
  createItemAction,
  updateItemAction,

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

export default slice.reducer;
