import { useMutation } from "@apollo/client/react";
import { Button } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useNavigate } 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_JOB } from "../../graphql/jobs.queries";
import { insertAuditTrail } from "../../redux/application/application.actions";
import { bodyshopHasDmsKey } from "../../utils/dmsUtils.js";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import AuditTrailMapping from "../../utils/AuditTrailMappings";
import client from "../../utils/GraphQLClient";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

const mapDispatchToProps = (dispatch) => ({
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

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

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

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

    setLoading(true);
    //Check if it's a QBO Setup.
    let PartnerResponse;
    if (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({
          title: 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({
          title: 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);
    const successfulTransactions = 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.error({
          // key: "failedexports",
          title: t("jobs.errors.exporting", {
            error: ft.errorMessage || ""
          })
        });
      });

      if (!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?.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.success({
            key: "jobsuccessexport",
            title: t("jobs.successes.exported")
          });
          insertAuditTrail({
            jobid: jobId,
            operation: AuditTrailMapping.jobexported(),
            type: "jobexported"
          });
          updateJobCache(jobUpdateResponse.data.update_jobs.returning.map((job) => job.id));
        } else {
          notification.error({
            title: t("jobs.errors.exporting", {
              error: JSON.stringify(jobUpdateResponse.error)
            })
          });
        }
      }
      if (bodyshop.accountingconfig?.qbo && successfulTransactions.length > 0) {
        notification.success({
          key: "jobsuccessexport",
          title: t("jobs.successes.exported")
        });
        insertAuditTrail({
          jobid: jobId,
          operation: AuditTrailMapping.jobexported(),
          type: "jobexported"
        });
        updateJobCache([
          ...new Set(successfulTransactions.map((st) => st[bodyshop.accountingconfig?.qbo ? "jobid" : "id"]))
        ]);
      }
      if (setSelectedJobs) {
        setSelectedJobs((selectedJobs) => {
          return selectedJobs.filter((i) => i !== jobId);
        });
      }
    }
    setLoading(false);
  };

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

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