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

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 = {
  isLoading: false,
  activeTabId: TAB_GENERAL,
  formChanged: false,

  playlistId: null,
  duplicatedPlaylistId: null,
  hubOptions: [],
  hub: null,
  name: '',
  status: true,
  url: '',
  isPrefix: true,
  playerOptions: [],
  player: null,
  playlistsByUrl: [],
  isFallback: false,
  shuffle: false,
  clips: [],

  // sponsored content
  includeSponsoredContent: false,
  frequency: 3,
  supplyTag: null,
  supplyTagOptions: null,

  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@EDITORIAL/SIDEBAR/PLAYLISTS/PLAYLIST_EDIT',
  initialState,

  reducers: {
    // common
    setIsLoadingAction: (state, action) => {
      state.isLoading = action.payload;
    },
    setActiveTabIdAction: (state, action) => {
      state.activeTabId = action.payload;
    },
    getPlaylistByIdAction: (state) => state,

    getHubOptionsAction: (state) => state,
    setHubOptionsAction: (state, action) => {
      state.hubOptions = action.payload;
    },

    getPlayerOptionsAction: (state) => state,
    setPlayerOptionsAction: (state, action) => {
      state.playerOptions = action.payload;
    },

    getPlaylistsByUrlAction: (state) => state,
    setPlaylistsByUrlAction: (state, action) => {
      state.playlistsByUrl = action.payload;
    },

    updateStoreByPropAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state[key] = action.payload[key];
      });
    },

    createPlaylistAction: (state) => state,
    updatePlaylistAction: (state) => state,
    duplicatePlaylistAction: (state) => state,
    clearCreateFormAction: (state) => ({ ...initialState, activeTabId: state.activeTabId }),
    getSupplyTagOptionsAction: (state) => state,

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

export const {
  setIsLoadingAction,
  setActiveTabIdAction,
  getPlaylistByIdAction,

  getHubOptionsAction,
  setHubOptionsAction,
  getPlayerOptionsAction,
  setPlayerOptionsAction,
  getPlaylistsByUrlAction,
  setPlaylistsByUrlAction,
  updateStoreByPropAction,

  createPlaylistAction,
  updatePlaylistAction,
  duplicatePlaylistAction,
  clearCreateFormAction,

  setScrollToFieldNameAction,
  setErrorByPropAction,
  removeErrorByPropAction,

  getSupplyTagOptionsAction,
} = slice.actions;

export default slice.reducer;
