import axios from 'axios';
import { formActionTypes } from '../../action-types/form-action.types';
import { formBuilderActionTypes } from '../../action-types/formBuilder-action.types';

/**
 * @description: Get all created forms
 * @param {*} getAllForms
 */
export const getAllForms = folder => async dispatch => {
  let url = '';
  if (folder && folder.length > 0) {
    url = `/forms?folder=${folder}&limit=1000000`;
  } else {
    url = '/forms?limit=10000000&folder=null';
  }
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_ALL_FORMS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const searchForms = query => async dispatch => {
  let url = '';
  if (query && query.length > 0) {
    url = `/forms/search?q=${query}`;
  } else {
    url = '/forms?limit=10000000&folder=null';
  }
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_ALL_FORMS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: Get all form folders
 * @param {*} getAllFolders
 */
export const getAllFolders = () => async dispatch => {
  const url = '/folders?limit=100000';
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_ALL_FOLDERS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: Create a new folder
 * @param {*} createFolder
 */
export const createFolder = folderDetails => async () => {
  const url = '/folders';
  try {
    const response = await axios.post(url, folderDetails);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const moveFormToFolder = (folderId, forms) => async () => {
  const url = `/folders/${folderId}/forms`;
  try {
    const response = await axios.post(url, forms);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * Create new form action
 * @param {*} formDetails
 */
export const createNewForm = formDetails => async () => {
  const url = '/forms';
  try {
    const response = await axios.post(url, formDetails);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * This function can also be used to reject entries
 * @param {*} acceptEntry
 */
export const acceptEntry = (entryId, status) => async () => {
  const url = `/entries/${entryId}/status`;
  try {
    const response = await axios.patch(url, status);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * This function can also be used to reject entries
 * @param {*} acceptEntry
 */
export const deleteEntry = entryId => async () => {
  const url = `/entries/${entryId}`;
  try {
    const response = await axios.delete(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: get the map location of the entry
 * @param {*} formId
 */
export const getEntryMap = formId => async dispatch => {
  const url = `/forms/${formId}/entries/map`;
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_ENTRY_MAP,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const addFormId = id => dispatch => {
  dispatch({
    type: formActionTypes.ADD_FORM_ID,
    payload: id,
  });
};

export const setActiveFolder = id => dispatch => {
  dispatch({
    type: formActionTypes.SET_ACTIVE_FOLDER,
    payload: id,
  });
};

export const savingForm = status => dispatch => {
  dispatch({
    type: formActionTypes.SAVING_FORM,
    payload: status,
  });
};

export const setCoverImage = imageUrl => dispatch => {
  dispatch({
    type: formActionTypes.SET_COVER_IMAGE,
    payload: imageUrl,
  });
};

export const updateForm = (formDetails, formId) => async dispatch => {
  const url = `/forms/${formId}`;
  dispatch({
    type: formBuilderActionTypes.UPDATING_FORM,
    payload: true,
  });
  try {
    const response = await axios.put(url, formDetails);
    const { success } = response.data;
    if (success) {
      dispatch({
        type: formBuilderActionTypes.UPDATING_FORM,
        payload: false,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      dispatch({
        type: formBuilderActionTypes.UPDATING_FORM,
        payload: false,
      });
      return error.response.data;
    }
  }
};

export const getFormPreview = formId => async dispatch => {
  const url = `/forms/${formId}`;
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_FORM_PREVIEW,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: add due date to a form share.
 * @param {*} date
 */
export const addFormDueDate = date => dispatch => {
  dispatch({
    type: formActionTypes.ADD_FORM_DUE_DATE,
    payload: date,
  });
};

export const allowValidation = value => dispatch => {
  dispatch({
    type: formActionTypes.SET_VALIDATION,
    payload: value,
  });
};

export const setNotification = value => dispatch => {
  dispatch({
    type: formActionTypes.SET_NOTIFICATION,
    payload: value,
  });
};

export const setTotalResponse = value => dispatch => {
  dispatch({
    type: formActionTypes.TOTAL_RESPONSE,
    payload: value,
  });
};

export const setAgentResponse = value => dispatch => {
  dispatch({
    type: formActionTypes.TOTAL_AGENT_RESPONSE,
    payload: value,
  });
};

export const updateDispatchName = value => dispatch => {
  dispatch({
    type: formActionTypes.SET_DISPATCH_NAME,
    payload: value,
  });
};

export const onAllowMultiResponse = value => dispatch => {
  dispatch({
    type: formActionTypes.ALLOW_MULTIPLE_RESPONSE,
    payload: value,
  });
};

export const shareForm = details => async dispatch => {
  const url = '/form-shares';
  try {
    const response = await axios.post(url, details);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.SHARED_FORM_DATA,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getSharedLinks = id => async dispatch => {
  const url = `/form-shares?form=${id}`;
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_SHARED_LINKS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getFormUsers = id => async dispatch => {
  const url = `/forms/${id}/users`;
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_FORM_USERS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const inViteFormUsers = (id, details) => async () => {
  const url = `/forms/${id}/users/invite`;
  try {
    const response = await axios.post(url, details);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const duplicateForm = id => async () => {
  const url = `/forms/duplicate/${id}`;
  try {
    const response = await axios.post(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: update folder details
 * @param {*} id
 * @param {*} details
 */
export const renameFolder = (id, details) => async () => {
  const url = `/folders/${id}`;
  try {
    const response = await axios.put(url, details);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const createTemplate = details => async () => {
  const url = '/templates';
  try {
    const response = await axios.post(url, details);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getTemplateCategories = () => async dispatch => {
  const url = '/template-categories';
  try {
    const response = await axios.get(url);
    const { success, data } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_TEMPLATE_CATEGORIES,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: Update folder name
 * @param {*} id
 * @param {*} details
 */
export const renameFolderName = (id, details) => async () => {
  const url = `/folders/${id}`;
  try {
    const response = await axios.put(url, details);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: delete a folder
 * @param {*} id
 * @param {*} details
 */
export const deleteFolder = id => async () => {
  const url = `/folders/${id}`;
  try {
    const response = await axios.delete(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description: Delete a created from from the list
 * @param {*} id
 */
export const deleteForm = id => async () => {
  const url = `/forms/${id}`;
  try {
    const response = await axios.delete(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const addFormToFolder = (folderId, forms) => async () => {
  const url = `/folders/${folderId}/forms`;
  try {
    const response = await axios.post(url, forms);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getResultSummary = formId => async dispatch => {
  const url = `/forms/${formId}/entries/summary`;
  try {
    const response = await axios.get(url);
    const { data, success } = response.data;
    if (success) {
      const allAnswers = [];
      data.summary.forEach(page => {
        allAnswers.push(page.summary);
      });
      dispatch({
        type: formActionTypes.GET_RESULT_SUMMARY,
        payload: allAnswers.flat(),
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getResponseList = formId => async dispatch => {
  const url = `/forms/${formId}/entries`;
  try {
    const response = await axios.get(url);
    const { data, success } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_RESPONSE_LIST,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const filterResponseList = (
  formId,
  filterBy,
  params
) => async dispatch => {
  let url = '';
  if (filterBy === 'date') {
    url = `/forms/${formId}/entries?startDate=${params.startDate}&endDate=${params.endDate}`;
  } else if (filterBy === 'status') {
    url = `/forms/${formId}/entries?status=${params}`;
  } else if (filterBy === 'formShare') {
    url = `/forms/${formId}/entries?formShare=${params}`;
  } else {
    url = `/forms/${formId}/entries`;
  }
  try {
    const response = await axios.get(url);
    const { data, success } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_RESPONSE_LIST,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const searchResponseList = (formId, query) => async dispatch => {
  let url = '';
  if (query.trim().length < 1) {
    url = `/forms/${formId}/entries`;
  } else {
    url = `/forms/${formId}/entries?query=${query}`;
  }
  try {
    const response = await axios.get(url);
    const { data, success } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_RESPONSE_LIST,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const getResponseDetails = (formId, entryId) => async dispatch => {
  const url = `/forms/${formId}/entries/${entryId}`;
  try {
    const response = await axios.get(url);
    const { data, success } = response.data;
    if (success) {
      dispatch({
        type: formActionTypes.GET_ENTRY_DETAILS,
        payload: data,
      });
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

/**
 * @description to get all entries tied to a for to be sent to the user's email
 * @param(formId)
 */
export const downloadAllEntries = formId => async () => {
  const url = `/forms/${formId}/entries/export`;
  try {
    const response = await axios.post(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};

export const suspendAgents = formId => async () => {
  const url = `/forms/${formId}/entries/export`;
  try {
    const response = await axios.post(url);
    const { success } = response.data;
    if (success) {
      return response.data;
    }
  } catch (error) {
    if (error.response) {
      return error.response.data;
    }
  }
};
