import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
import axios from "axios";
import _ from "lodash";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import { auth, logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_EXPORT_LOG } from "../../graphql/accounting.queries";
import { UPDATE_BILLS } from "../../graphql/bills.queries";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import client from "../../utils/GraphQLClient";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

function updateBillCache(items) {
  client.cache.modify({
    id: "ROOT_QUERY",
    fields: {
      bills(existingJobs = []) {
        return existingJobs.filter((billRef) => billRef.__ref.includes(items) === false);
      }
    }
  });
}

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

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

    setLoading(true);
    if (loadingCallback) loadingCallback(true);
    if (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({
          title: 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({
          title: 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);
          const successfulTransactions = groupedData[key].filter((r) => r.success);
          if (failedTransactions.length > 0) {
            //Uh oh. At least one was no good.
            failedTransactions.map((ft) =>
              notification.error({
                title: t("bills.errors.exporting", {
                  error: ft.errorMessage || ""
                })
              })
            );
            if (!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?.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: successfulTransactions.map((st) => st[bodyshop.accountingconfig?.qbo ? "billid" : "id"]),
                  bill: {
                    exported: true,
                    exported_at: new Date()
                  }
                }
              });
              if (!billUpdateResponse.errors) {
                notification.success({
                  key: "billsuccessexport",
                  title: t("bills.successes.exported")
                });
                updateBillCache(billUpdateResponse.data.update_bills.returning.map((bill) => bill.id));
              } else {
                notification.error({
                  title: t("bills.errors.exporting", {
                    error: JSON.stringify(billUpdateResponse.errors)
                  })
                });
              }
            }
            if (bodyshop?.accountingconfig?.qbo && successfulTransactions.length > 0) {
              notification.success({
                key: "billsuccessexport",
                title: t("bills.successes.exported")
              });
              updateBillCache([
                ...new Set(successfulTransactions.map((st) => st[bodyshop.accountingconfig?.qbo ? "billid" : "id"]))
              ]);
            }
          }
        })()
      );
    });

    await Promise.all(proms);
    if (completedCallback) completedCallback([]);
    if (loadingCallback) loadingCallback(false);
    setLoading(false);
  };

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

  return (
    <Button onClick={handleQbxml} loading={loading} disabled={disabled || billids?.length > 10} type="primary">
      {t("jobs.actions.exportselected")}
    </Button>
  );
}

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