import { Menu, notification } from "antd";
import axios from "axios";
import React from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { auth, logImEXEvent } from "../../firebase/firebase.utils";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});
const mapDispatchToProps = (dispatch) => ({});

export function JobsDetailHeaderActionexportCustomerData({
  bodyshop,
  job,
  ...props
}) {
  const { t } = useTranslation();

  const handleExportCustData = async (e) => {
    logImEXEvent("job_export_cust_data");
    let PartnerResponse;
    if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) {
      PartnerResponse = await axios.post(`/qbo/receivables`, {
        jobIds: [job.id],
        custDataOnly: true,
      });
    } else {
      //Default is QBD

      let QbXmlResponse;
      try {
        QbXmlResponse = await axios.post(
          "/accounting/qbxml/receivables",
          { jobIds: [job.id], custDataOnly: true },
          {
            headers: {
              Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
            },
          }
        );
        console.log("handle -> XML", QbXmlResponse);
      } catch (error) {
        console.log("Error getting QBXML from Server.", error);
        notification["error"]({
          message: t("jobs.errors.exporting", {
            error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
          }),
        });

        return;
      }

      //let PartnerResponse;
      try {
        PartnerResponse = await axios.post(
          "http://localhost:1337/qb/",
          QbXmlResponse.data,
          {
            headers: {
              Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
            },
          }
        );
      } catch (error) {
        console.log("Error connecting to quickbooks or partner.", error);
        notification["error"]({
          message: t("jobs.errors.exporting-partner"),
        });

        return;
      }
    }
    //Check to see if any of them failed. If they didn't don't execute the update.
    const failedTransactions = PartnerResponse.data.filter((r) => !r.success);
    if (failedTransactions.length > 0) {
      //Uh oh. At least one was no good.
      failedTransactions.forEach((ft) => {
        //insert failed export log
        notification.open({
          // key: "failedexports",
          type: "error",
          message: t("jobs.errors.exporting", {
            error: ft.errorMessage || "",
          }),
        });
      });

      //Handle Failures.
    } else {
      //Insert success export log.

      notification.open({
        type: "success",
        key: "jobsuccessexport",
        message: t("jobs.successes.exported"),
      });
    }
  };

  return (
    <Menu.Item
      {...props}
      onClick={handleExportCustData}
      key="exportcustdata"
      disabled={!job.converted}
    >
      {t("jobs.actions.exportcustdata")}
    </Menu.Item>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(JobsDetailHeaderActionexportCustomerData);
