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

import { FILTERS, STATUS_FILTERS } from '../../../common/constants';

const initialState = {
  accounts: [],
  page: 0,
  totalCount: 0,
  rowsPerPage: 25,
  search: '',
  sortBy: 'REQUESTS',
  sortOrder: 'DESC',
  filterDate: FILTERS[0].value,
  filterByStatus: STATUS_FILTERS[1].value,
  isLoading: false,
  pageConfig: null,
  activeTabIndex: 0,
  userHubs: [],
  userDemandAccounts: [],
  modal: null,
};

export const slice = createSlice({
  name: '@@accounts/ACCOUNTS',
  initialState,
  reducers: {
    setFieldAction: (state, action) => {
      Object.entries(action.payload).forEach(([key, value]) => {
        state[key] = value;
      });
    },
    setDefaultConfigAction: (state, action) => {
      const config = {
        ...initialState,
        userHubs: state.userHubs,
        userDemandAccounts: state.userDemandAccounts,
        ...action.payload,
      };

      Object.keys(config).forEach((key) => {
        state[key] = config[key];
      });
    },
    setHubsAndDemandAccountsAction: (state, action) => {
      state.userHubs = action.payload?.userHubs ?? [];
      state.userDemandAccounts = action.payload?.userDemandAccounts ?? [];
    },
    setActiveTabIndexAction: (state, action) => {
      state.activeTabIndex = action.payload;
    },
    setSortByAction: (state, action) => {
      state.sortBy = action.payload;
    },
    setSortOrderAction: (state, action) => {
      state.sortOrder = action.payload;
    },
    setFilterDateAction: (state, action) => {
      state.filterDate = action.payload;
    },
    setFilterByStatusAction: (state, action) => {
      state.filterByStatus = action.payload;
    },
    setSearchAction: (state, action) => {
      state.search = action.payload;
    },
    setRowsPerPageAction: (state, action) => {
      state.rowsPerPage = action.payload;
    },

    getAccountsAction: (state) => state,
    getNextAccountsAction: (state) => state,
    refreshPageDataByIntervalAction: (state) => state,
    downloadCSVAction: (state) => state,
    saveToCSVAction: (state) => state,
    getHubsAndDemandAccountsAction: (state) => state,
  },
});

export const {
  setFieldAction,
  setDefaultConfigAction,
  setHubsAndDemandAccountsAction,
  setActiveTabIndexAction,
  setSortByAction,
  setSortOrderAction,
  setFilterDateAction,
  setFilterByStatusAction,
  setSearchAction,
  setRowsPerPageAction,
  getAccountsAction,
  getNextAccountsAction,
  refreshPageDataByIntervalAction,
  downloadCSVAction,
  saveToCSVAction,
  getHubsAndDemandAccountsAction,
} = slice.actions;

export default slice.reducer;
