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

import {
  GENERAL_TAB,
  PLAYER_REDUX_FIELD_NAME,
  SWIPE_ANIMATION_DURATION,
  SWIPE_ANIMATION_MAX_VISITS,
  VERTICAL_FULLSCREEN_TITLE_TIMELINE_VISIBILITY_ALWAYS,
} from '@/modules/players/Editor/constants';

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

const formSlice = createFormSlice(PLAYER_REDUX_FIELD_NAME, validationScheme);

export const { validateFields, validateSingleField } = formSlice;

//TODO: Player defaults values always received from backend with getPlayerUiProps
// src/modules/players/Editor/redux/epics/getPlayerData.js

const initialState = {
  id: 0,
  type: 0,
  playerType: null,
  name: '',
  status: 1,
  activeTabId: GENERAL_TAB,
  availableTemplatePlayers: [],
  /// GENERAL TAB ///
  publisherId: 0,
  publishersOptions: null,
  publisher: null,
  alias: '',
  publisherDomainId: 0,
  publisherDomainsOptions: [],
  publisherDomain: null,
  comments: '',
  /// LOOK AND FEEL TAB ///
  playerLreLogo: null,
  playerWidth: 0,
  playerWidthUnit: '',
  playerWidthMobile: 0,
  playerWidthMobileUnit: '',
  playerWidthUnitOptions: [],
  playerAspectRatio: '',
  playerAspectRatioOptions: [],
  playerDynamicAspectRatioOptions: [],
  brandingLeft: '',
  brandingRight: '',
  brandingRightDefault: '',
  carouselEnabled: 0,
  carouselEnabledMobile: 0,
  carouselOrientation: '',
  carouselOrientationOptions: [],
  closedCaptioning: '',
  closedCaptioningOptions: [],
  videoResolutionControl: 0,
  playbackSpeedControl: 0,
  fullScreen: 0,
  chapteringMenuNavigation: 0,
  chapteringTimeline: 0,
  theaterMode: 0,
  ffRewind: 0,
  socialViewButton: 0,
  socialLikeButton: 0,
  xRayCampaignsEnabled: 0,
  leftBrandingColor: '',
  leftBrandingSize: 0,
  leftBrandingSizeOptions: [],
  verticalFullscreenTitleTimelineVisibility: VERTICAL_FULLSCREEN_TITLE_TIMELINE_VISIBILITY_ALWAYS,
  swipeAnimation: true,
  swipeAnimationMaxVisits: SWIPE_ANIMATION_MAX_VISITS,
  swipeAnimationDuration: SWIPE_ANIMATION_DURATION,
  progressBarColor: '',
  timestampTooltipColor: '',
  volumeBarColor: '',
  settingsMenuHighlightColor: '',
  /// FLOATING TAB ///
  floatingDesktopEnabled: 0,
  floatingDesktopEnabledOptions: [],
  floatingDesktopMode: '',
  floatingDesktopModeOptions: [],
  floatingDesktopPosition: '',
  floatingDesktopPositionOptions: [],
  floatingDesktopWidth: 0,
  floatingDesktopWidthVertical: 0,
  floatingDesktopDelay: 0,
  floatingMobileEnabled: 0,
  delayCloseIconEnabledMobile: 0,
  floatingMobileEnabledOptions: [],
  floatingMobileMode: '',
  floatingMobileModeOptions: [],
  floatingMobilePosition: '',
  floatingMobilePositionOptions: [],
  floatingMobileWidth: 0,
  floatingMobileWidthVertical: 0,
  floatingMobileDelay: 0,
  /// CONTENT FILTERS TAB ///
  useDefaultContentOwner: 0,
  allFeeds: 0,
  playerContentOwnerFeeds: [],
  playerContentOwnerFeedsOptions: [],
  playerBrandSafeties: [],
  brandSafetiesOptions: [],
  playerFeedLanguages: [],
  feedLanguagesOptions: [],
  boosts: [],
  boostsTypesOptions: [],
  boostsListOptions: [],
  /// PLAYBACK TAB ///
  autoplayDesktop: 0,
  autoplayMobile: 0,
  autoplayOptions: [],
  startWithSound: 0,
  startWithSoundMobile: 0,
  startWithSoundOptions: [],
  playlistLimit: 0,
  flowTermId: 0,
  editorialEnabled: 0,
  editorialType: '',
  flowTermsOptions: [],
  playInLoop: 0, // value only for UI
  playInLoopOptions: [],
  loopPlaylist: 0,
  adsOnLoopOff: 0,
  shufflePlaylist: 0,
  clipAutomaticSkipOptions: null,
  clipAutomaticSkipEnabled: 0,
  clipAutomaticSkipTimeToPresent: 0,
  clipAutomaticSkipTimeToSkip: 0,
  playerEditorialPlaylistId: 0,
  editorialPlaylist: null,
  playerEditorialPlaylistsOptions: null,
  /// VIDEO ADS TAB ///
  adManagerDesktop: 0,
  fallbackDisplayMonetizationDesktop: true,
  adManagerMobile: 0,
  fallbackDisplayMonetizationMobile: true,
  clipNotInViewPlayAdsDesktop: 0,
  clipNotInViewPlayAdsMobile: 0,
  maxAdsPerClipChecked: 0,
  maxAdsPerClip: 0,
  maxAdsPerClipOptions: [],
  firstAdRequestDelay: 0,
  preRollOptions: null,
  preRoll: 0,
  preRollWaitMs: 0,
  prerollOnly: false,
  prerollOnlyClipsCount: 1,
  adIndicator: 0,
  adIndicatorText: '',
  skipAdButton: 0,
  skipAdAppearAfter: 1,
  skipAdAppearAfterDefault: 1,
  inviewAdInterval: 0,
  notInviewAdInterval: 0,
  inviewAdIntervalMobile: 0,
  notInviewAdIntervalMobile: 0,
  /// DISPLAY ADS TAB ///
  displayMonetizationDesktop: 0,
  displayMonetizationMobile: 0,
  displayClipNotInViewPlayAdsDesktop: 0,
  displayClipNotInViewPlayAdsMobile: 0,
  displayInviewAdInterval: 0,
  displayNotInviewAdInterval: 0,
  displayInviewAdIntervalMobile: 0,
  displayNotInviewAdIntervalMobile: 0,
  abTest: false,
  enableVideoTargeting: false,
  videoFormatByDevice: false,
  isLoading: true,

  /// CUSTOM PLACEHOLDER TAB ///
  customPlaceholderEnable: false,
  selectors: [],

  ...formSlice.state,
};

export const slice = createSlice({
  name: '@@PLAYER/EDITOR',
  initialState,
  reducers: {
    setDefaultsAction: (state, action) => ({ ...state, ...action.payload }),

    setAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setObjectValuesAction: (state, action) => {
      const keys = Object.keys(action.payload);
      keys.forEach((key) => {
        if (key) {
          state[key] = { ...state[key], ...action.payload[key] };
        }
      });
    },
    setOppositeAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state[key] = state[key] ? 0 : 1;
      });
    },
    setInitialAction: () => ({
      ...initialState,
    }),
    getPlayerDataAction: (state) => state,
    getPublishersOptionsAction: (state) => state,
    getPlayerFeedsOptionsAction: (state) => state,
    getPlayerBoostListOptionsAction: (state) => state,
    getPlayerEditorialPlaylistsOptionsAction: (state) => state,
    createPlayerAction: (state) => state,
    updatePlayerAction: (state) => state,
    setPlayerIsLoadingAction: (state, action) => {
      state.isLoading = action.payload;
    },
    setSelectorsAction: (state, action) => {
      state.selectors = action.payload;
    },
    setSelectorAction: (state, action) => {
      state.selectors.push(action.payload);
    },
    setSelectorValuesAction: (state, action) => {
      const index = state.selectors.findIndex((item) => item.id === action.payload.id);
      if (index !== -1) {
        state.selectors[index].selector = action.payload.selector;
      }
    },
    deleteSelectorAction: (state, action) => {
      const index = state.selectors.findIndex((item) => item.id === action.payload.id);
      if (index !== -1) {
        state.selectors.slice(index, 1);
      }
    },
    setActiveTabIdAction: (state, action) => {
      state.activeTabId = action.payload;
    },
    setScrollToFieldNameAction: formSlice.actions.setScrollToFieldAction,
    setErrorByPropAction: formSlice.actions.updateValidationSchemeAction,
    removeErrorByPropAction: formSlice.actions.removeErrorByFieldNameAction,
  },
});

export const {
  setDefaultsAction,
  setAction,
  setObjectValuesAction,
  setInitialAction,
  setOppositeAction,
  getPlayerDataAction,
  getAccountOptionsAction,
  getPublishersOptionsAction,
  getPlayerFeedsOptionsAction,
  getPlayerBoostListOptionsAction,
  getPlayerEditorialPlaylistsOptionsAction,
  setPlayerIsLoadingAction,
  createPlayerAction,
  updatePlayerAction,
  setSelectorAction,
  setSelectorValuesAction,
  deleteSelectorAction,
  setSelectorsAction,

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

export default slice.reducer;
