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

import { STATUSES_ACTIVE } 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 = {
  account: null,
  accountOptions: [],
  publisherIds: [],
  lookerReportId: null,
  allSites: 0,
  uiName: '',
  description: '',
  enabled: STATUSES_ACTIVE,
  icon: '',

  activeTabId: TAB_GENERAL,

  ...formSlice.state,
};

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

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

export default slice.reducer;
