import { createSlice, type PayloadAction } from '@reduxjs/toolkit';

import { ROWS_PER_PAGE_DEFAULT, TABLE_REDUX_FIELD_NAME, TABLE_SORT_BY } from '../../constants';
import { SORT_DESC } from '@/modules/@common/constants/sort';
import { AD_FORMAT_CONFIG_ALL, CALENDAR_FILTER_THIS_MONTH } from '@/modules/analytics/monetization/constants';

import type { StateTableSliceType, StateType } from '../../types';

import { applyPartial } from '@/modules/@common/store/helpers';
import createTableSlice from '@/modules/@common/Table/redux/slices';

const tableSlice = createTableSlice(TABLE_REDUX_FIELD_NAME, {
  page: 1,
  pageSize: ROWS_PER_PAGE_DEFAULT,
  sortBy: TABLE_SORT_BY,
  sortOrder: SORT_DESC,
});

const initialState: StateType = {
  [TABLE_REDUX_FIELD_NAME]: {
    ...(tableSlice.state as Record<typeof TABLE_REDUX_FIELD_NAME, StateTableSliceType>)[TABLE_REDUX_FIELD_NAME],
  },

  // filters
  adFormat: AD_FORMAT_CONFIG_ALL,
  period: CALENDAR_FILTER_THIS_MONTH,

  customDateFrom: '',
  customDateTo: '',

  // todo: save only values but not label + value for all autocompletes
  devices: [],

  demandSources: [],
  demandSourcesOptions: [],

  players: [],
  playersOptions: [],

  domains: [],
  domainsOptions: [],

  countriesFullList: [],
  countries: [],
  countriesOptions: [],
};

export const slice = createSlice({
  name: '@@ANALYTICS/REVENUE_OVERVIEW',
  initialState,

  reducers: {
    getDataAction: tableSlice.actions.getTableDataAction,
    setAction: (state: StateType, action: PayloadAction<Partial<StateType>>) => {
      applyPartial<StateType>(state, action.payload, [TABLE_REDUX_FIELD_NAME]);
    },
    setTableAction: (state: StateType, action: PayloadAction<Partial<StateTableSliceType>>) =>
      tableSlice.actions.setTableAction(state, action),
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getPlayersAction: (state: StateType, action: PayloadAction<string | undefined>) => state,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getDomainsAction: (state: StateType, action: PayloadAction<string | undefined>) => state,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getCountriesFullListAction: (state: StateType, action: PayloadAction<string | undefined>) => state,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getCountriesAction: (state: StateType, action: PayloadAction<string | undefined>) => state,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    getDemandSourcesAction: (state: StateType, action: PayloadAction<string | undefined>) => state,
    exportToCsvAction: (state: StateType) => state,
  },
});

export const {
  getDataAction,
  setTableAction,
  setAction,
  getPlayersAction,
  getDomainsAction,
  getCountriesAction,
  getCountriesFullListAction,
  getDemandSourcesAction,
  exportToCsvAction,
} = slice.actions;
