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,
  hub: null,
  hubOptions: null,
  name: '',
  title: '',
  image: '',
  buttonLabel1: '',
  buttonUrl1: '',
  buttonLabel2: '',
  buttonUrl2: '',
  impressionTracker: '',
  clickTracker1: '',
  clickTracker2: '',

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

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

  setActiveTabIdAction,

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

export default slice.reducer;
