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

import {
  ROWS_PER_PAGE_DEFAULT,
  STATUSES_ALL,
  STATUSES_REVOKED,
  TABLE_REDUX_FIELD_NAME,
  TABLE_SORT_BY,
} from '../../constants';
import { SORT_DESC } from '@/modules/@common/constants/sort';

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 = {
  // table
  ...tableSlice.state,

  // filters
  search: '',
  account: null,
  accountOptions: null, // null need for loading state
  status: STATUSES_ALL,
};

export const slice = createSlice({
  name: '@@INVITATIONS/LIST',
  initialState,

  reducers: {
    getDataAction: tableSlice.actions.getTableDataAction,
    setTableAction: tableSlice.actions.setTableAction,
    setAction: (state, action) => {
      Object.keys(action.payload).forEach((key) => {
        state[key] = action.payload[key];
      });
    },
    getAccountOptionsAction: (state) => state,
    revokeAction: (state) => state,
    revokeActionSuccess: (state, action) => {
      const index = state[TABLE_REDUX_FIELD_NAME].data.findIndex((row) => row.id === action.payload);

      state[TABLE_REDUX_FIELD_NAME].data[index].invStatus = STATUSES_REVOKED;
    },
  },
});

export const { getDataAction, setTableAction, setAction, getAccountOptionsAction, revokeAction, revokeActionSuccess } =
  slice.actions;
