import type { PayloadAction } from '@reduxjs/toolkit';
import { createSlice } 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 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
  searchText: '',
  status: null,
};

export const slice = createSlice({
  name: '@@FEEDS/SELF_SERVE_LIST',
  initialState,
  reducers: {
    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),
    getDataAction: tableSlice.actions.getTableDataAction,
    importArchivedAction: (
      state: StateType,
      action: PayloadAction<{ feedId: number; date: Date | null; isEmailNotification: boolean }>,
    ) => {
      if (action.payload) {
        return state;
      }
      return state;
    },
  },
});

export const { getDataAction, setTableAction, setAction, importArchivedAction } = slice.actions;
