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

import { IS_PUBLIC_NO, STATUSES_ACTIVE, TYPE_PUBLISHER } 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,
  name: '',
  salesforceId: '',
  comments: '',
  playFromCo: false,
  callToAction: false,
  account: null,
  accountOptions: null,
  type: TYPE_PUBLISHER,
  status: STATUSES_ACTIVE,
  isPublic: IS_PUBLIC_NO,
  feedPriority: 0.5,

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@CONTENT_OWNERS/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,

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

export const {
  setAction,
  setInitialAction,
  getItemAction,
  getAccountOptionsAction,
  createItemAction,
  updateItemAction,

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

export default slice.reducer;
