import { useMutation } from "@apollo/client/react";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import Axios from "axios";
import Dinero from "dinero.js";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { INSERT_NEW_JOB_LINE, UPDATE_JOB_LINE } from "../../graphql/jobs-lines.queries";
import { toggleModalVisible } from "../../redux/modals/modals.actions";
import { selectJobLineEditModal } from "../../redux/modals/modals.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import CriticalPartsScan from "../../utils/criticalPartsScan";
import UndefinedToNull from "../../utils/undefinedtonull";
import JobLinesUpdsertModal from "./job-lines-upsert-modal.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import AuditTrailMapping from "../../utils/AuditTrailMappings.js";
import { insertAuditTrail } from "../../redux/application/application.actions.js";
import { buildJobLineInsertAuditDetails, buildJobLineUpdateAuditDetails } from "../../utils/auditTrailDetails.js";

const mapStateToProps = createStructuredSelector({
  jobLineEditModal: selectJobLineEditModal,
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  toggleModalVisible: () => dispatch(toggleModalVisible("jobLineEdit")),
  insertAuditTrail: ({ jobid, operation, type }) => dispatch(insertAuditTrail({ jobid, operation, type }))
});

function JobLinesUpsertModalContainer({ jobLineEditModal, toggleModalVisible, bodyshop, insertAuditTrail }) {
  const {
    treatments: { CriticalPartsScanning }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["CriticalPartsScanning"],
    splitKey: bodyshop.imexshopid
  });
  const notification = useNotification();

  const { t } = useTranslation();
  const [insertJobLine] = useMutation(INSERT_NEW_JOB_LINE);
  const [updateJobLine] = useMutation(UPDATE_JOB_LINE);
  const [loading, setLoading] = useState(false);

  const handleFinish = async (values) => {
    setLoading(true);
    if (!jobLineEditModal.context.id) {
      const r = await insertJobLine({
        variables: {
          lineInput: [
            {
              jobid: jobLineEditModal.context.jobid,
              manual_line: !jobLineEditModal.context?.id,
              ...UndefinedToNull({
                ...values,
                prt_dsmk_m: Dinero({
                  amount: Math.round((values.act_price || 0) * 100)
                })
                  .percentage(Math.abs(values.prt_dsmk_p || 0))
                  .multiply(values.prt_dsmk_p >= 0 ? 1 : -1)
                  .toFormat(0.0)
              })
            }
          ]
        },
        refetchQueries: ["GET_LINE_TICKET_BY_PK"]
      });
      if (!r.errors) {
        if (CriticalPartsScanning.treatment === "on") {
          await CriticalPartsScan(jobLineEditModal.context.jobid, notification);
        }
        await Axios.post("/job/totalsssu", {
          id: jobLineEditModal.context.jobid
        });
        if (jobLineEditModal.actions.refetch) jobLineEditModal.actions.refetch();
        //Need to recalcuate totals.
        toggleModalVisible();
        notification.success({
          title: t("joblines.successes.created")
        });
        insertAuditTrail({
          jobid: jobLineEditModal.context.jobid,
          operation: AuditTrailMapping.jobmanuallineinsert(buildJobLineInsertAuditDetails(values)),
          type: "jobmanuallineinsert"
        });
      } else {
        notification.error({
          title: t("joblines.errors.creating", {
            message: JSON.stringify(r.errors.message)
          })
        });
      }
    } else {
      const r = await updateJobLine({
        variables: {
          lineId: jobLineEditModal.context.id,
          line: {
            ...UndefinedToNull({
              ...values,
              prt_dsmk_m: Dinero({
                amount: Math.round(values.act_price * 100)
              })
                .percentage(Math.abs(values.prt_dsmk_p || 0))
                .multiply(values.prt_dsmk_p >= 0 ? 1 : -1)
                .toFormat(0.0)
            })
          }
        },
        refetchQueries: ["GET_LINE_TICKET_BY_PK"]
      });
      if (!r.errors) {
        notification.success({
          title: t("joblines.successes.updated")
        });
        insertAuditTrail({
          jobid: jobLineEditModal.context.jobid,
          operation: AuditTrailMapping.joblineupdate(
            values.line_desc || jobLineEditModal.context.line_desc || "manual line",
            buildJobLineUpdateAuditDetails({
              originalLine: jobLineEditModal.context,
              values
            })
          ),
          type: "joblineupdate"
        });
      } else {
        notification.success({
          title: t("joblines.errors.updating", {
            message: JSON.stringify(r.errors.message)
          })
        });
      }
      if (CriticalPartsScanning.treatment === "on") {
        await CriticalPartsScan(jobLineEditModal.context.jobid, notification);
      }
      if (jobLineEditModal.actions.submit) {
        jobLineEditModal.actions.submit();
      } else {
        if (jobLineEditModal.actions.refetch) jobLineEditModal.actions.refetch();
      }
      toggleModalVisible();
    }

    setLoading(false);
  };

  const handleCancel = () => {
    toggleModalVisible();
  };

  return (
    <JobLinesUpdsertModal
      open={jobLineEditModal.open}
      jobLine={jobLineEditModal.context}
      handleFinish={handleFinish}
      handleCancel={handleCancel}
      loading={loading}
    />
  );
}

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