import { useMutation } from "@apollo/client";
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, logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_PAYMENTS } from "../../graphql/payments.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";

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

export function PaymentExportButton({
  bodyshop,
  paymentId,
  disabled,
  loadingCallback,
}) {
  const { t } = useTranslation();
  const [updatePayment] = useMutation(UPDATE_PAYMENTS);
  const [loading, setLoading] = useState(false);

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

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

    let QbXmlResponse;
    try {
      QbXmlResponse = await axios.post(
        "/accounting/qbxml/payments",
        { payments: [paymentId] },
        {
          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("payments.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/",
        //"http://609feaeae986.ngrok.io/qb/",
        QbXmlResponse.data
      );
    } catch (error) {
      console.log("Error connecting to quickbooks or partner.", error);
      notification["error"]({
        message: t("payments.errors.exporting-partner"),
      });
      if (!!loadingCallback) loadingCallback(false);
      setLoading(false);
      return;
    }

    console.log("handleQbxml -> PartnerResponse", PartnerResponse);
    const failedTransactions = 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("payments.errors.exporting", {
            error: ft.errorMessage || "",
          }),
        })
      );
    } else {
      const paymentUpdateResponse = await updatePayment({
        variables: {
          paymentIdList: [paymentId],
          payment: {
            exportedat: new Date(),
          },
        },
      });
      if (!!!paymentUpdateResponse.errors) {
        notification["success"]({
          message: t("payments.successes.exported"),
        });
      } else {
        notification["error"]({
          message: t("payments.errors.exporting", {
            error: JSON.stringify(paymentUpdateResponse.error),
          }),
        });
      }
    }

    if (!!loadingCallback) loadingCallback(false);
    setLoading(false);
  };

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

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