import axios from "axios";
import moment from "moment";
import { Dispatch } from "redux";

import {
    DRAFT_ANSWERS,
    GET_AUDIT_FORM_DATA_FAILED,
    GET_AUDIT_FORM_DATA_REQUEST,
    GET_AUDIT_FORM_DATA_SUCCESS,
    REMOVE_DRAFT_ANSWERS,
    SUBMIT_AUDIT_FAILED,
    SUBMIT_AUDIT_REQUEST,
    SUBMIT_AUDIT_SUCCESS,
} from "./types";

import config from '../../config/config';

import { axiosErrorMessage } from "../../utils/helper";
import { addHistory } from "./historyScreenActions";

/**
 * Save a draft answer for a given form
 */
export const draftAnswer = (draftValues: any, formId: string) => {
  return (dispatch: Dispatch) => {
    dispatch({
      type: DRAFT_ANSWERS,
      payload: { draftValues, formId },
    });
  };
};

/**
 * Remove a draft after successful submission
 */
export const removeSubmittedFormDraft = (formId: string) => {
  return (dispatch: Dispatch) => {
    dispatch({
      type: REMOVE_DRAFT_ANSWERS,
      payload: formId,
    });
  };
};

/**
 * Fetch Audit form types and locations
 */
export const getAuditFormData = () => {
  return async (dispatch: Dispatch) => {
    dispatch({ type: GET_AUDIT_FORM_DATA_REQUEST });

    try {
      const res = await axios.get(
        `${config.apiserver}/api/v1/audit/get-audit-types-and-locations`
      );
      dispatch({
        type: GET_AUDIT_FORM_DATA_SUCCESS,
        payload: res.data,
      });
    } catch (error: any) {
      console.error("GET_AUDIT_FORM_DATA_FAILED", error);
      axiosErrorMessage(
        "Something went wrong while fetching audit form data. Try to sync again",
        error
      );
      dispatch({
        type: GET_AUDIT_FORM_DATA_FAILED,
        payload: error,
      });
    }
  };
};

/**
 * Submit an audit form with answers, files and actions
 */
export const submitAudit = (
  data: Record<string, any>,
  auditFormId: string,
  selectedEntity: string,
  auditTypeId: string,
  token: string,
  selectedBUManager: string
) => {
  const formData = new FormData();
  const keys: string[] = [];
  const allData: Record<string, any> = {};

  allData[auditFormId] = {
    id: auditTypeId,
    entity_id: selectedEntity,
    selectedBUManager,
  };

  const actions: any[] = [];

  Object.entries(data).forEach(([key, value]) => {
    let questionId = "";

    if (key.includes("_actions") && value?.body?.length > 0) {
      actions.push(value);
    }

    if (key.includes("_answer")) {
      questionId = key.replace("_answer", "");
      allData[auditFormId][questionId] = {
        ...allData[auditFormId][questionId],
        composite_radio_webform_custom_composite: value,
      };
    }

    if (key.includes("_observation")) {
      questionId = key.replace("_observation", "");
      allData[auditFormId][questionId] = {
        ...allData[auditFormId][questionId],
        composite_textarea_webform_custom_composite: value,
      };
    }

    if (key.includes("_uri") && Array.isArray(value) && value.length > 0) {
      questionId = key.replace("_uri", "");
      const filenames: string[] = [];

      value.forEach((img: any) => {
        const fileKey = `imageKey_${questionId}image${img.key}`;
        const extension =
          img.name?.substring(img.name.lastIndexOf(".") + 1) ||
          (img.type === "video/mp4" ? "mp4" : "jpg");

        const filename = `${questionId}image${img.key}.${extension}`;
        filenames.push(filename);

        keys.push(fileKey);

        formData.append(fileKey, {
          uri: img.uri,
          type: img.type,
          name: filename,
        } as any);
      });

      allData[auditFormId][questionId] = {
        ...allData[auditFormId][questionId],
        composite_file_webform_custom_composite: filenames.join(),
      };
    }
  });

  allData[auditFormId]["actions"] = actions;

  formData.append("submission_data", JSON.stringify(allData));
  if (keys.length > 0) {
    formData.append("image_keys", keys.join());
  }

  // Add history
  const formattedDate = moment().format("DD-MM-YYYY");
  const formattedTime = moment().format("h:mm:ss a");
  addHistory({
    title: `${auditFormId} submitted on ${formattedDate} at ${formattedTime}`,
    data: formData,
    url: `${config.apiserver}/api/v1/audit/webform-submission`,
  });

  return {
    type: SUBMIT_AUDIT_REQUEST,
    payload: formData,
    meta: {
      offline: {
        effect: {
          url: `${config.apiserver}/api/v1/audit/webform-submission`,
          method: "post",
          data: formData,
          headers: { Accept: "*/*", Authorization: `Bearer ${token}` },
        },
        commit: { type: SUBMIT_AUDIT_SUCCESS },
        rollback: {
          type: SUBMIT_AUDIT_FAILED,
          meta: {
            title: auditFormId,
            url: `${config.apiserver}/api/v1/audit/webform-submission`,
            data: formData,
          },
        },
      },
    },
  };
};

/**
 * Validate audit/inspection submission
 */
export const auditOrInspectionSubmissionValiation = (
  id: string,
  entity_id: string
) => {
  return async () => {
    const formData = new FormData();
    formData.append("id", id);
    formData.append("entity_id", entity_id);

    try {
      const res = await axios.post(
        `${config.apiserver}/api/v1/question/form-submission-validaton`,
        formData
      );
      return res;
    } catch (error) {
      console.error("auditSubmissionValiation error =>", error);
      return error;
    }
  };
};
