import { StoreAction } from 'store/utils/actions';
import produce from 'immer';
import {
  handleRequest,
  handleResponse,
  handleUpdateResponse,
  handleAddResponse,
  handleDeleteResponse,
} from 'store/utils/reducers';
import auth from 'store/auth';
import _ from 'lodash';
import actions from './actions';

interface FormsState {
  list: {} | null;
  detail: {} | null;
  result: {} | null;
}

export const initialState: FormsState = {
  list: null,
  detail: null,
  result: null,
};

const treatList = (item): Record<string, any> => {
  const newItem = { ...item };

  return newItem;
};

const reducer = (state: FormsState = initialState, action: StoreAction): FormsState =>
  produce(
    state,
    (draft): FormsState => {
      let send;
      switch (action.type) {
        case actions.list.request.constant:
          handleRequest(draft, action, 'list', true);
          break;
        case actions.list.result.constant:
          handleResponse(draft, action, 'list', treatList);
          break;
        case actions.update.result.constant:
          handleUpdateResponse(draft, action, 'list', treatList);
          break;
        case actions.add.result.constant:
          handleAddResponse(draft, action, 'list', treatList);
          break;
        case actions.delete.result.constant:
          handleDeleteResponse(draft, action, 'list', treatList);
          break;
        case actions.detail.result.constant:
          draft.detail = _.omit(action.payload, 'submissions');
          send = {
            ...action,
            payload: _.pick(action.payload, 'submissions'),
          };
          handleResponse(draft, send, 'result', treatList);
          break;
        case actions.detailFormData.result.constant:
          draft.detail = action.payload;
          break;
        case auth.actions.logout.result.constant:
          draft.list = null;
          draft.detail = null;
          break;
        default:
      }
    },
  );

export default reducer;
