import { useMutation } from "@apollo/react-hooks";
import { Button, notification } from "antd";
import axios from "axios";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { auth } from "../../firebase/firebase.utils";
import { UPDATE_INVOICES } from "../../graphql/invoices.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { logImEXEvent } from "../../firebase/firebase.utils";

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

export function InvoiceExportAllButton({
  bodyshop,
  invoiceIds,
  disabled,
  loadingCallback,
  completedCallback,
}) {
  const { t } = useTranslation();
  const [updateInvoice] = useMutation(UPDATE_INVOICES);
  const [loading, setLoading] = useState(false);

  const handleQbxml = async () => {
    logImEXEvent("accounting_payables_export_all");

    setLoading(true);
    if (!!loadingCallback) loadingCallback(true);

    let QbXmlResponse;
    try {
      QbXmlResponse = await axios.post(
        "/accounting/qbxml/payables",
        { invoices: invoiceIds },
        {
          headers: {
            Authorization: `Bearer ${await auth.currentUser.getIdToken(true)}`,
          },
        }
      );
      console.log("handle -> XML", QbXmlResponse);
    } catch (error) {
      console.log("Error getting QBXML from Server.", error);
      notification["error"]({
        message: t("invoices.errors.exporting", {
          error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
        }),
      });
      if (loadingCallback) loadingCallback(false);
      setLoading(false);
      return;
    }

    let PartnerResponse;

    try {
      PartnerResponse = await axios.post(
        "http://localhost:1337/qb/",
        QbXmlResponse.data
      );
    } catch (error) {
      console.log("Error connecting to quickbooks or partner.", error);
      notification["error"]({
        message: t("invoices.errors.exporting-partner"),
      });
      if (!!loadingCallback) loadingCallback(false);
      setLoading(false);
      return;
    }

    console.log("handleQbxml -> PartnerResponse", PartnerResponse);
    const failedTransactions = PartnerResponse.data.filter((r) => !r.success);
    const successfulTransactions = PartnerResponse.data.filter(
      (r) => r.success
    );
    if (failedTransactions.length > 0) {
      //Uh oh. At least one was no good.
      failedTransactions.map((ft) =>
        notification["error"]({
          message: t("invoices.errors.exporting", {
            error: ft.errorMessage || "",
          }),
        })
      );
    }
    if (successfulTransactions.length > 0) {
      const invoiceUpdateResponse = await updateInvoice({
        variables: {
          invoiceIdList: successfulTransactions.map((st) => st.id),
          invoice: {
            exported: true,
            exported_at: new Date(),
          },
        },
      });
      if (!!!invoiceUpdateResponse.errors) {
        notification["success"]({
          message: t("jobs.successes.exported"),
        });
      } else {
        notification["error"]({
          message: t("jobs.errors.exporting", {
            error: JSON.stringify(invoiceUpdateResponse.error),
          }),
        });
      }
    }

    //Set the list of selected invoices to be nothing.
    if (!!completedCallback) completedCallback([]);
    if (!!loadingCallback) loadingCallback(false);
    setLoading(false);
  };

  return (
    <Button
      onClick={handleQbxml}
      loading={loading}
      disabled={disabled}
      type='dashed'>
      {t("jobs.actions.exportselected")}
    </Button>
  );
}

export default connect(mapStateToProps, null)(InvoiceExportAllButton);
