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

import { FILTERS } from '../../../common/constants';
import {
  AUTOMATIC_OPTIMIZATION,
  AUTOMATIC_OPTIMIZATION_FREQUENCY,
  AUTOMATIC_OPTIMIZATION_KPI_VIDEO,
  AUTOMATIC_OPTIMIZATION_PERIOD,
  AUTOMATIC_OPTIMIZATION_TIERS,
  CHART_TABS,
  DEMAND_TAG_DEFAULT_TIER_VALUES,
  DEMAND_TAG_FORMAT,
  DEMAND_TAG_FREQUENCY_CAP_TIMEFRAME_LIST,
  DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST,
  DEMAND_TAG_FREQUENCY_TAB_STATUS,
  DEMAND_TAG_KEY_VALUE_TARGETING_STATUS,
  DEMAND_TAG_PAGE_AD_SERVER_TYPE_VALUES,
  DEMAND_TAG_PAGE_BUSINESS_MODEL,
  DEMAND_TAG_PAGE_DEVICE_LIST,
  DEMAND_TAG_PAGE_OS_LIST,
  DEMAND_TAG_PAGE_TYPE_VALUES,
  DEMAND_TAG_PRICING_TYPE,
  DEMAND_TAG_PRIORITY,
  DEMAND_TAG_STATUS,
  DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE,
  DEMAND_TAG_SUPPLY_CHAIN_VALUE,
  DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE,
  DEMAND_TAG_TARGETING_VIEWABILITY_TYPE,
  DEMAND_TAG_VIEWABILITY_TARGETING,
  FLOOR_PRICE,
  SOURCE_TAG_OPTIONS,
  STATUS_ACTIVE,
  SUPPLY_TAG_PUBLISHER_DEMAND_ONLY,
} from '../../constants';
import { DEMAND_ADVERTISER_SETTINGS_VALIDATION_REDUX_FIELD } from '@/modules/marketplace/account/components/AdvertiserSettings/constants';

import createFormSlice from '@/modules/@common/Form/redux/slices';
import { validationScheme as advertiserSettingsValidationScheme } from '@/modules/marketplace/account/components/AdvertiserSettings/helpers/validationScheme';

export const advertiserSettingsValidationSlice = createFormSlice(
  DEMAND_ADVERTISER_SETTINGS_VALIDATION_REDUX_FIELD,
  advertiserSettingsValidationScheme,
);

const initialModalState = {
  id: null,
  data: [],
  totalCount: 0,
  page: 0,
  search: '',
  accountsOptions: [],
  status: {
    ...STATUS_ACTIVE,
  },
  isFetchingData: false,
  rate: '',
  model: null,
  label: null,
  labelsOptions: [],
  displayType: null,
};

const initialState = {
  pageConfig: null,
  activeTabIndex: 0,
  filterByDate: FILTERS[0].value,
  filterByStatus: null,
  filterByCountry: null,
  filterByDevice: null,
  filterByLabel: null,
  filterByPlayer: { label: 'All Players', value: null },
  filterByPlayerOptions: [],
  labelsOptions: [],
  info: null,
  total: {},
  data: [],
  totalCount: 0,
  page: 0,
  rowsPerPage: 25,
  search: '',
  sortBy: 'REQUESTS',
  sortOrder: 'DESC',
  isLoading: false,
  chartTab: CHART_TABS[0].value,
  chartData: [],
  chartHistory: [],
  isChartLoading: false,
  timeIntervalFilter: null,
  comparisonFilter: null,
  userHubs: [],
  userDemandAccounts: [],
  demandAccountInfo: null,
  modal: {
    ...initialModalState,
  },
  supply: {
    name: '',
    source: SOURCE_TAG_OPTIONS[0].value,
    displayType: null,
    platformId: '',
    floorPrice: {
      floor: '',
      viewableFloor: '',
      firstRequestFloor: '',
    },
    adServerUrl: '',
    waterfallNote: '',
    pricing: [],
    expenses: [],
    format: DEMAND_TAG_FORMAT.video, // video || display
    publisherDemandOnly: SUPPLY_TAG_PUBLISHER_DEMAND_ONLY.disabled,
    automaticFloorPrice: false,
    fillRateThreshold: '',
    minimumFloor: '',
    maximumFloor: '',
    errors: {},
  },
  automaticOptimization: {
    status: AUTOMATIC_OPTIMIZATION.enabled,
    kpi: AUTOMATIC_OPTIMIZATION_KPI_VIDEO[6].value,
    period: AUTOMATIC_OPTIMIZATION_PERIOD[5].value,
    frequency: AUTOMATIC_OPTIMIZATION_FREQUENCY[2].value,
    hbTiers: AUTOMATIC_OPTIMIZATION_TIERS[1].value,
    kpiGap: '45',
    errors: {},
  },
  budgeting: {
    budgetingTabList: [],
    isInitializeFromInfo: false,
  },
  frequencyCap: {
    status: DEMAND_TAG_FREQUENCY_TAB_STATUS.active,
    type: DEMAND_TAG_FREQUENCY_CAP_TYPE_LIST.request,
    value: 2,
    timeframe: DEMAND_TAG_FREQUENCY_CAP_TIMEFRAME_LIST[0].value,
    amount: 1,
    prevSavedData: null,
  },
  pricing: {
    model: DEMAND_TAG_PAGE_BUSINESS_MODEL[0].value,
    source: null,
    seatId: '',
    type: null,
    adUnitId: '',
    fixedRpmRateList: [],
    additionalFeesList: [],
    fixedRpmRateTable: {
      rows: [],
      page: 0,
      totalCount: 0,
      rowsPerPage: 5, // value re-initialized in getPricingTab epic
      type: DEMAND_TAG_PRICING_TYPE.price,
    },
    adServingFeesTable: {
      rows: [],
      page: 0,
      totalCount: 0,
      rowsPerPage: 5, // value re-initialized in getPricingTab epic
      type: DEMAND_TAG_PRICING_TYPE.adServing,
    },
    additionalFeesTable: {
      rows: [],
      page: 0,
      totalCount: 0,
      rowsPerPage: 5, // value re-initialized in getPricingTab epic
      type: DEMAND_TAG_PRICING_TYPE.fee,
    },
    adRequestFeesTable: {
      rows: [],
      page: 0,
      totalCount: 0,
      rowsPerPage: 5, // value re-initialized in getPricingTab epic
      type: DEMAND_TAG_PRICING_TYPE.adRequest,
    },
    publisherDemand: null,
    errors: {},
  },
  settings: {
    name: '',
    source: SOURCE_TAG_OPTIONS[0].value,
    platformId: '',
    format: DEMAND_TAG_FORMAT.video, // video || display
    status: DEMAND_TAG_STATUS.enabled, // enabled || disabled
    flightsDates: null,
    uid: '',
    advertiser: '',
    demandAccount: '',
    type: DEMAND_TAG_PAGE_TYPE_VALUES.tag, // tag || hb
    supplyChainOverride: DEMAND_TAG_SUPPLY_CHAIN_OVERRIDE.disabled, // enabled || disabled
    supplyChainValue: DEMAND_TAG_SUPPLY_CHAIN_VALUE.blank, // blank || custom
    supplyChainNode: '',
    floorPrice: {
      override: FLOOR_PRICE.publisherDefault,
      floor: '',
      viewableFloor: '',
    },
    maxFloor: 15,
    adjustFloor: true,
    bidMappingFileName: '',
    bidMappingFileData: [],
    adServerType: DEMAND_TAG_PAGE_AD_SERVER_TYPE_VALUES.none, // none || list
    adServer: {},
    adServersList: [], // options for select
    url: '',
    priority: DEMAND_TAG_PRIORITY.openAuction,
    defaultTier: DEMAND_TAG_DEFAULT_TIER_VALUES[3].value,
    labels: [],
    timeout: 20000,
    eventPixelsList: [],
    platform: {},
    platforms: [],
    videoId: '',
    clickThroughUrl: '',
    errors: {},
  },
  targeting: {
    viewability: {
      [DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.inView]: true,
      [DEMAND_TAG_TARGETING_VIEWABILITY_TYPE.nonInView]: true,
    },
    viewabilityTargeting: DEMAND_TAG_VIEWABILITY_TARGETING.disabled,
    viewabilityThreshold: '',
    playerSize: {
      [DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.xs]: true,
      [DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.s]: true,
      [DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.m]: true,
      [DEMAND_TAG_TARGETING_PLAYER_SIZE_TYPE.l]: true,
    },
    devices: DEMAND_TAG_PAGE_DEVICE_LIST.map((device) => ({ ...device, include: true })),
    countries: [],
    os: DEMAND_TAG_PAGE_OS_LIST.map((device) => ({ ...device, include: true })),
    browsers: [],
    countriesList: [], // options for select, used also in advertiser settings tab
    kvTargetingStatus: DEMAND_TAG_KEY_VALUE_TARGETING_STATUS.disabled, // enabled || disabled
    kvTargeting: [],
    keyNamesOptions: [],
    keyListsOptions: [],
    errors: {},
  },
  advertiserSettings: {
    countries: [],
    tier: 2,
    name: '',
    demandAccountId: null,
    revShare: [],
    pbsEnabled: false,
    profitability: true,
    frequencyCapAdjustmentPerSupply: true,
    frequencyCapAdjustment: true,
    frequencyCapAdjustmentThreshold: 0.01,
    errors: {},
    logo: '',
    logoFile: null,
  },
  ...advertiserSettingsValidationSlice.state,
};

export const slice = createSlice({
  name: '@@account/ACCOUNT',
  initialState,
  reducers: {
    setFieldAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setDefaultConfigAction: (state, action) => {
      const config = { ...initialState, ...(action.payload ?? {}) };
      Object.keys(config).forEach((key) => {
        state[key] = config[key];
      });
    },
    setActiveTabIndexAction: (state, action) => {
      state.activeTabIndex = action.payload;
    },
    setFilterByDateAction: (state, action) => {
      state.filterByDate = action.payload;
    },
    setFilterByStatusAction: (state, action) => {
      state.filterByStatus = action.payload;
    },
    setFilterByCountryAction: (state, action) => {
      state.filterByCountry = action.payload;
    },
    setFilterByDeviceAction: (state, action) => {
      state.filterByDevice = action.payload;
    },
    setFilterByLabelAction: (state, action) => {
      state.filterByLabel = action.payload;
    },
    setFilterByPlayerAction: (state, action) => {
      state.filterByPlayer = action.payload;
    },
    setLabelsOptionsAction: (state, action) => {
      state.labelsOptions = action.payload;
    },
    setRowsPerPageAction: (state, action) => {
      state.rowsPerPage = action.payload;
    },
    setSearchAction: (state, action) => {
      state.search = action.payload;
    },
    setSortByAction: (state, action) => {
      state.sortBy = action.payload;
    },
    setSortOrderAction: (state, action) => {
      state.sortOrder = action.payload;
    },
    setChartTabAction: (state, action) => {
      state.chartTab = action.payload;
    },
    setTimeIntervalFilterAction: (state, action) => {
      state.timeIntervalFilter = action.payload;
    },
    setComparisonFilterAction: (state, action) => {
      state.comparisonFilter = action.payload;
    },
    openModalAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.modal[key] = action.payload[key];
      });
    },
    setModalInfoAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.modal[key] = action.payload[key];
      });
    },
    closeModalAction: (state) => {
      Object.keys(initialModalState).forEach((key) => {
        state.modal[key] = initialModalState[key];
      });
    },
    setBudgetingTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.budgeting[key] = action.payload[key];
      });
    },
    setFrequencyCapTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.frequencyCap[key] = action.payload[key];
      });
    },
    setPricingTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.pricing[key] = action.payload[key];
      });
    },
    setSettingsTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.settings[key] = action.payload[key];
      });
    },
    setTargetingTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.targeting[key] = action.payload[key];
      });
    },
    setAdvertiserSettingsTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.advertiserSettings[key] = action.payload[key];
      });
    },
    setSupplyTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.supply[key] = action.payload[key];
      });
    },
    setAutomaticOptimizationTabAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state.automaticOptimization[key] = action.payload[key];
      });
    },
    resetDemandFormAction: (state) => {
      Object.keys(initialState.settings).forEach((key) => {
        state.settings[key] = initialState.settings[key];
      });
      Object.keys(initialState.frequencyCap).forEach((key) => {
        state.frequencyCap[key] = initialState.frequencyCap[key];
      });
      Object.keys(initialState.budgeting).forEach((key) => {
        state.budgeting[key] = initialState.budgeting[key];
      });

      const targeting = {
        ...initialState.targeting,
        countriesList: state.targeting.countriesList,
      };

      Object.keys(targeting).forEach((key) => {
        state.targeting[key] = targeting[key];
      });
    },
    resetSupplyFormAction: (state) => {
      const supply = {
        ...initialState.supply,
        price: state.supply.price,
      };

      Object.keys(supply).forEach((key) => {
        state.supply[key] = supply[key];
      });
    },
    setHubsAndDemandAccountsAction: (state, action) => {
      state.userHubs = action.payload?.userHubs ?? [];
      state.userDemandAccounts = action.payload?.userDemandAccounts ?? [];
    },

    getInfoAction: (state) => state,
    getDataAction: (state) => state,
    getTotalAction: (state) => state,
    createSupplyTagsAction: (state) => state,
    getChartDataAction: (state) => state,
    updateWaterfallAction: (state) => state,
    updateTiersAction: (state) => state,
    deleteWaterfallAction: (state) => state,
    getDataForWaterfallAction: (state) => state,
    getAccountsForWaterfallAction: (state) => state,
    getLabelsForTableFilterAction: (state) => state,
    getLabelsForWaterfallAction: (state) => state,
    bulkCreateWaterfallAction: (state) => state,
    refreshPageDataByIntervalAction: (state) => state,
    validateTagAction: (state) => state,
    downloadCSVAction: (state) => state,
    saveToCSVAction: (state) => state,
    getHistoryForCSVAction: (state) => state,
    getHistoryForChartAction: (state) => state,
    showConfirmModalAction: (state) => state,
    // demand
    getBudgetingTabAction: (state) => state,
    getFrequencyCapTabAction: (state) => state,
    getPricingTabAction: (state) => state,
    getSettingsTabAction: (state) => state,
    getTargetingTabAction: (state) => state,
    getAdvertiserSettingsTabAction: (state) => state,
    getAdServerListsAction: (state) => state,
    getCountriesListAction: (state) => state,
    createDemandTagAction: (state) => state,
    updateDemandTagAction: (state) => state,
    bulkUpdateDemandTagAction: (state) => state,
    bulkUpdateViewabilityThresholdAction: (state) => state,
    initializeDemandFormDataAction: (state) => state,
    duplicateDemandTagAction: (state) => state,
    getDemandTagPricingAction: (state) => state,
    getPlatformsAction: (state) => state,
    createAdvertiserAction: (state) => state,
    updateAdvertiserAction: (state) => state,
    initializeAdvertiserFormDataAction: (state) => state,
    getKeyNamesOptionsAction: (state) => state,
    getKeyListsOptionsAction: (state) => state,
    getDemandAccountByIdAction: (state) => state,
    validateAdvertiserAction: (state) => state,
    getHubsAndDemandAccountsAction: (state) => state,
    // supply
    createSupplyTagAction: (state) => state,
    initializeSupplyFormDataAction: (state) => state,
    bulkUpdateSupplyTagAction: (state) => state,
    updateSupplyTagAction: (state) => state,
    duplicateSupplyTagAction: (state) => state,
    getAutomaticOptimizationTabAction: (state) => state,
    getFilterByPlayerOptionsAction: (state) => state,
    // validations
    advertiserSettingsValidationSetScrollToFieldNameAction:
      advertiserSettingsValidationSlice.actions.setScrollToFieldAction,
    advertiserSettingsValidationSetErrorByPropAction:
      advertiserSettingsValidationSlice.actions.updateValidationSchemeAction,
    advertiserSettingsValidationRemoveErrorByPropAction:
      advertiserSettingsValidationSlice.actions.removeErrorByFieldNameAction,
  },
});

export const {
  setFieldAction,
  setDefaultConfigAction,
  setActiveTabIndexAction,
  setFilterByDateAction,
  setFilterByStatusAction,
  setFilterByCountryAction,
  setFilterByDeviceAction,
  setFilterByLabelAction,
  setFilterByPlayerAction,
  setLabelsOptionsAction,
  setRowsPerPageAction,
  setSearchAction,
  setSortByAction,
  setSortOrderAction,
  setChartTabAction,
  setTimeIntervalFilterAction,
  setComparisonFilterAction,
  openModalAction,
  setModalInfoAction,
  closeModalAction,
  setBudgetingTabAction,
  setFrequencyCapTabAction,
  setPricingTabAction,
  setSettingsTabAction,
  setTargetingTabAction,
  setAdvertiserSettingsTabAction,
  setSupplyTabAction,
  setAutomaticOptimizationTabAction,
  resetDemandFormAction,
  resetSupplyFormAction,
  setHubsAndDemandAccountsAction,

  getInfoAction,
  getDataAction,
  getTotalAction,
  createSupplyTagsAction,
  getChartDataAction,
  updateWaterfallAction,
  updateTiersAction,
  deleteWaterfallAction,
  getDataForWaterfallAction,
  getAccountsForWaterfallAction,
  getLabelsForTableFilterAction,
  getLabelsForWaterfallAction,
  bulkCreateWaterfallAction,
  refreshPageDataByIntervalAction,
  validateTagAction,
  downloadCSVAction,
  saveToCSVAction,
  getHistoryForCSVAction,
  getHistoryForChartAction,
  showConfirmModalAction,
  // demand
  getBudgetingTabAction,
  getFrequencyCapTabAction,
  getPricingTabAction,
  getSettingsTabAction,
  getTargetingTabAction,
  getAdvertiserSettingsTabAction,
  getAdServerListsAction,
  getCountriesListAction,
  createDemandTagAction,
  updateDemandTagAction,
  bulkUpdateDemandTagAction,
  bulkUpdateViewabilityThresholdAction,
  initializeDemandFormDataAction,
  duplicateDemandTagAction,
  getDemandTagPricingAction,
  getPlatformsAction,
  createAdvertiserAction,
  updateAdvertiserAction,
  initializeAdvertiserFormDataAction,
  getKeyNamesOptionsAction,
  getKeyListsOptionsAction,
  getDemandAccountByIdAction,
  validateAdvertiserAction,
  getHubsAndDemandAccountsAction,
  // supply
  createSupplyTagAction,
  initializeSupplyFormDataAction,
  bulkUpdateSupplyTagAction,
  updateSupplyTagAction,
  duplicateSupplyTagAction,
  getAutomaticOptimizationTabAction,
  getFilterByPlayerOptionsAction,

  // validation for advertiser demand settings page
  advertiserSettingsValidationSetScrollToFieldNameAction,
  advertiserSettingsValidationSetErrorByPropAction,
  advertiserSettingsValidationRemoveErrorByPropAction,
} = slice.actions;

export default slice.reducer;
