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

import { STATUSES_ACTIVE, TYPE_VIDEO } from '../../../List/constants';
import { FORM_REDUX_FIELD_NAME, TAB_GENERAL } from '../../constants';

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

const formSlice = createFormSlice(FORM_REDUX_FIELD_NAME, validationScheme);

export const { validateFields, validateSingleField } = formSlice;

const initialState = {
  name: '',
  status: STATUSES_ACTIVE,
  url: '',
  placementId: TYPE_VIDEO,
  isDefaultForPlayerType: false,
  playerTypesIds: [],
  playerTypesOptions: [],
  macro: '',
  comments: '',

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

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

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

export const {
  setAction,
  setInitialAction,
  getPlayerTypesOptionsAction,
  getItemAction,
  createItemAction,
  updateItemAction,
  setScrollToFieldNameAction,
  setErrorByPropAction,
  removeErrorByPropAction,
} = slice.actions;

export default slice.reducer;
