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

import { ALL, ROWS_PER_PAGE_DEFAULT, STATUS_PEOPLE, 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, {
  pageSize: ROWS_PER_PAGE_DEFAULT,
  sortBy: TABLE_SORT_BY,
  sortOrder: SORT_DESC,
  page: 0,
});

const initialState = {
  // table
  ...tableSlice.state,

  // filters
  search: '',
  accountId: null,
  category: STATUS_PEOPLE,
  accountOptions: [],
  languages: [],
  xrayStatus: ALL,
  image: ALL,
  tagStatus: ALL,

  // loader
  isMergeLoading: false,
};

export const slice = createSlice({
  name: '@@ENTITIES/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,
    getLanguages: (state) => state,
    updateEntityAction: (state) => state,
    createEntityAction: (state) => state,
    addEntityAction: (state, { payload }) => {
      state[TABLE_REDUX_FIELD_NAME].data.unshift(payload);
    },
    updateLocalEntityAction: (state, { payload }) => {
      const index = state[TABLE_REDUX_FIELD_NAME].data.findIndex((item) => item.id === payload.id);
      state[TABLE_REDUX_FIELD_NAME].data[index] = payload;
    },
    mergeEntitiesAction: (state) => state,
  },
});

export const {
  getDataAction,
  setTableAction,
  setAction,
  getLanguages,
  getAccountOptionsAction,
  updateEntityAction,
  createEntityAction,
  addEntityAction,
  updateLocalEntityAction,
  mergeEntitiesAction,
} = slice.actions;
