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

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

export function JobsCloseExportButton({
  bodyshop,
  currentUser,
  jobId,
  disabled,
  setSelectedJobs,
  refetch,
}) {
  const history = useHistory();
  const { t } = useTranslation();
  const [updateJob] = useMutation(UPDATE_JOB);
  const [insertExportLog] = useMutation(INSERT_EXPORT_LOG);
  const [loading, setLoading] = useState(false);

  const handleQbxml = async () => {
    //Check if it's a CDK setup.
    if (bodyshop.cdk_dealerid || bodyshop.pbs_serialnumber) {
      history.push(`/manage/dms?jobId=${jobId}`);
      return;
    }
    logImEXEvent("jobs_close_export");

    setLoading(true);
    //Check if it's a QBO Setup.
    let PartnerResponse;
    if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) {
      PartnerResponse = await axios.post(`/qbo/receivables`, {
        jobIds: [jobId],
        elgen: true,
      });
    } else {
      //Default is QBD

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

      try {
        PartnerResponse = await axios.post(
          "http://localhost:1337/qb/",
          // "http://609feaeae986.ngrok.io/qb/",
          QbXmlResponse.data,
          {
            headers: {
              Authorization: `Bearer ${await auth.currentUser.getIdToken()}`,
            },
          }
        );
      } catch (error) {
        console.log("Error connecting to quickbooks or partner.", error);
        notification["error"]({
          message: t("jobs.errors.exporting-partner"),
        });
        setLoading(false);
        return;
      }
    }

    console.log("PartnerResponse", PartnerResponse);

    //Check to see if any of them failed. If they didn't don't execute the update.
    const failedTransactions = PartnerResponse.data.filter((r) => !r.success);
    if (failedTransactions.length > 0) {
      //Uh oh. At least one was no good.
      failedTransactions.forEach((ft) => {
        //insert failed export log
        notification.open({
          // key: "failedexports",
          type: "error",
          message: t("jobs.errors.exporting", {
            error: ft.errorMessage || "",
          }),
        });
      });

      if (!(bodyshop.accountingconfig && bodyshop.accountingconfig.qbo)) {
        //QBO Logs are handled server side.
        await insertExportLog({
          variables: {
            logs: [
              {
                bodyshopid: bodyshop.id,
                jobid: jobId,
                successful: false,
                message: JSON.stringify(
                  failedTransactions.map((ft) => ft.errorMessage)
                ),
                useremail: currentUser.email,
              },
            ],
          },
        });
      }
    } else {
      //Insert success export log.
      if (!(bodyshop.accountingconfig && bodyshop.accountingconfig.qbo)) {
        //QBO Logs are handled server side.
        await insertExportLog({
          variables: {
            logs: [
              {
                bodyshopid: bodyshop.id,
                jobid: jobId,
                successful: true,
                useremail: currentUser.email,
              },
            ],
          },
        });

        const jobUpdateResponse = await updateJob({
          variables: {
            jobId: jobId,
            job: {
              status: bodyshop.md_ro_statuses.default_exported || "Exported*",
              date_exported: new Date(),
            },
          },
        });

        if (!jobUpdateResponse.errors) {
          notification.open({
            type: "success",
            key: "jobsuccessexport",
            message: t("jobs.successes.exported"),
          });
        } else {
          notification["error"]({
            message: t("jobs.errors.exporting", {
              error: JSON.stringify(jobUpdateResponse.error),
            }),
          });
        }
      }
      if (setSelectedJobs) {
        setSelectedJobs((selectedJobs) => {
          return selectedJobs.filter((i) => i !== jobId);
        });
      }
    }
    if (bodyshop.accountingconfig && bodyshop.accountingconfig.qbo) refetch();
    setLoading(false);
  };

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

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