import { useMutation } from "@apollo/client";
import { useSplitTreatments } from "@splitsoftware/splitio-react";
import Axios from "axios";
import Dinero from "dinero.js";
import React, { 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";

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

function JobLinesUpsertModalContainer({ jobLineEditModal, toggleModalVisible, bodyshop }) {
  const {
    treatments: { CriticalPartsScanning }
  } = useSplitTreatments({
    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 && 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"]({
          message: t("joblines.successes.created")
        });
      } else {
        notification["error"]({
          message: 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"]({
          message: t("joblines.successes.updated")
        });
      } else {
        notification["success"]({
          message: 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);
