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 } from "../../firebase/firebase.utils";
import { UPDATE_BILLS } from "../../graphql/bills.queries";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
import { logImEXEvent } from "../../firebase/firebase.utils";
import _ from "lodash";
import { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
import { Link } from "react-router-dom";

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

export function PayableExportAll({
  bodyshop,
  currentUser,
  billids,
  disabled,
  loadingCallback,
  completedCallback,
  refetch,
}) {
  const { t } = useTranslation();
  const [updateBill] = useMutation(UPDATE_BILLS);
  const [loading, setLoading] = useState(false);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);

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

    setLoading(true);
    if (!!loadingCallback) loadingCallback(true);
    if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) {
      PartnerResponse = await axios.post(`/qbo/payables`, {
        bills: billids,
        elgen: true,
      });
    } else {
      let QbXmlResponse;
      try {
        QbXmlResponse = await axios.post(
          "/accounting/qbxml/payables",
          { bills: billids },
          {
            headers: {
              Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
            },
          }
        );
      } catch (error) {
        console.log("Error getting QBXML from Server.", error);
        notification["error"]({
          message: t("bills.errors.exporting", {
            error: "Unable to retrieve QBXML. " + JSON.stringify(error.message),
          }),
        });
        if (loadingCallback) loadingCallback(false);
        setLoading(false);
        return;
      }

      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("bills.errors.exporting-partner"),
        });
        if (!!loadingCallback) loadingCallback(false);
        setLoading(false);
        return;
      }
    }

    console.log("handleQbxml -> PartnerResponse", PartnerResponse);
    const groupedData = _.groupBy(
      PartnerResponse.data,
      bodyshop.accountingconfig.qbo ? "billid" : "id"
    );

    const proms = [];
    Object.keys(groupedData).forEach((key) => {
      proms.push(
        (async () => {
          const failedTransactions = groupedData[key].filter((r) => !r.success);

          if (failedTransactions.length > 0) {
            //Uh oh. At least one was no good.
            failedTransactions.map((ft) =>
              notification["error"]({
                message: t("bills.errors.exporting", {
                  error: ft.errorMessage || "",
                }),
              })
            );
            if (!(bodyshop.accountingconfig && bodyshop.accountingconfig.qbo)) {
              //QBO Logs are handled server side.
              await insertExportLog({
                variables: {
                  logs: [
                    {
                      bodyshopid: bodyshop.id,
                      billid: key,
                      successful: false,
                      message: JSON.stringify(
                        failedTransactions.map((ft) => ft.errorMessage)
                      ),
                      useremail: currentUser.email,
                    },
                  ],
                },
              });
            }
          } else {
            if (!(bodyshop.accountingconfig && bodyshop.accountingconfig.qbo)) {
              //QBO Logs are handled server side.
              await insertExportLog({
                variables: {
                  logs: [
                    {
                      bodyshopid: bodyshop.id,
                      billid: key,
                      successful: true,
                      useremail: currentUser.email,
                    },
                  ],
                },
              });

              const billUpdateResponse = await updateBill({
                variables: {
                  billIdList: [key],
                  bill: {
                    exported: true,
                    exported_at: new Date(),
                  },
                },
              });
              if (!!!billUpdateResponse.errors) {
                notification.open({
                  type: "success",
                  key: "billsuccessexport",
                  message: t("bills.successes.exported"),
                });
              } else {
                notification["error"]({
                  message: t("bills.errors.exporting", {
                    error: JSON.stringify(billUpdateResponse.error),
                  }),
                });
              }
            }
          }
        })()
      );
    });

    await Promise.all(proms);
    if (!!completedCallback) completedCallback([]);
    if (!!loadingCallback) loadingCallback(false);
    if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) refetch();

    setLoading(false);
  };

  if (bodyshop.pbs_serialnumber)
    return (
      <Link to={{ state: { billids }, pathname: `/manage/dmsap` }}>
        <Button>{t("jobs.actions.export")}</Button>
      </Link>
    );

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

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