import { useMutation } from "@apollo/client";
import { Button, notification } from "antd";
import axios from "axios";
import _ from "lodash";
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 { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
import { UPDATE_PAYMENTS } from "../../graphql/payments.queries";
import {
  selectBodyshop,
  selectCurrentUser,
} from "../../redux/user/user.selectors";
const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  currentUser: selectCurrentUser,
});

export function PaymentsExportAllButton({
  bodyshop,
  currentUser,
  paymentIds,
  disabled,
  loadingCallback,
  completedCallback,
}) {
  const { t } = useTranslation();
  const [updatePayments] = useMutation(UPDATE_PAYMENTS);
  const [loading, setLoading] = useState(false);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);

  const handleQbxml = async () => {
    setLoading(true);
    if (!!loadingCallback) loadingCallback(true);

    let QbXmlResponse;
    try {
      QbXmlResponse = await axios.post(
        "/accounting/qbxml/payments",
        { payments: paymentIds },
        {
          headers: {
            Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
          },
        }
      );
    } 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/",
        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;
    }

    const groupedData = _.groupBy(PartnerResponse.data, "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("payments.errors.exporting", {
                  error: ft.errorMessage || "",
                }),
              })
            );
            await insertExportLog({
              variables: {
                logs: [
                  {
                    bodyshopid: bodyshop.id,
                    paymentid: key,
                    successful: false,
                    message: JSON.stringify(
                      failedTransactions.map((ft) => ft.errorMessage)
                    ),
                    useremail: currentUser.email,
                  },
                ],
              },
            });
          } else {
            await insertExportLog({
              variables: {
                logs: [
                  {
                    bodyshopid: bodyshop.id,
                    paymentid: key,
                    successful: true,
                    useremail: currentUser.email,
                  },
                ],
              },
            });
            const paymentUpdateResponse = await updatePayments({
              variables: {
                paymentIdList: [key],
                payment: {
                  exportedat: new Date(),
                },
              },
            });
            if (!!!paymentUpdateResponse.errors) {
              notification.open({
                type: "success",
                key: "paymentsuccessexport",
                message: t("payments.successes.exported"),
              });
            } else {
              notification["error"]({
                message: t("payments.errors.exporting", {
                  error: JSON.stringify(paymentUpdateResponse.error),
                }),
              });
            }
          }
        })()
      );
    });
    await Promise.all(proms);
    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)(PaymentsExportAllButton);
