import { useMutation } from "@apollo/client/react";
import { Card, Form } from "antd";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useLocation, useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { INSERT_NEW_CONTRACT } from "../../graphql/cccontracts.queries";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import ContractCreatePageComponent from "./contract-create.page.component";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils.js";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = (dispatch) => ({
  setBreadcrumbs: (breadcrumbs) => dispatch(setBreadcrumbs(breadcrumbs)),
  setSelectedHeader: (key) => dispatch(setSelectedHeader(key))
});

export function ContractCreatePageContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const [form] = Form.useForm();
  const { t } = useTranslation();

  const history = useNavigate();
  const location = useLocation();
  const [loading, setLoading] = useState(false);
  const selectedCarState = useState(null);
  const selectedJobState = useState((location.state && location.state.jobId) || null);

  const [insertContract] = useMutation(INSERT_NEW_CONTRACT);
  const [intakeJob] = useMutation(UPDATE_JOB);
  const notification = useNotification();

  const handleFinish = async ({ addtoproduction, ...values }) => {
    if (!!selectedCarState[0] && !!selectedJobState[0]) {
      setLoading(true);
      const result = await insertContract({
        variables: {
          ccId: selectedCarState[0].id,
          damage: values.damage,
          mileage: values.kmstart,
          contract: {
            ...values,
            status: "contracts.status.out",
            courtesycarid: selectedCarState[0].id,
            jobid: selectedJobState[0]
          }
        }
      });

      if (!result.errors) {
        //Update the courtesy car to have the damage.
        logImEXEvent("courtesy_car_contract_created", {});
        notification.success({
          title: t("contracts.successes.saved")
        });

        //Intake the job if required
        if (addtoproduction) {
          const result2 = await intakeJob({
            variables: {
              jobId: selectedJobState[0],
              job: {
                actual_in: new Date(),
                inproduction: true,
                status: bodyshop.md_ro_statuses.default_arrived
              }
            }
          });
          if (result2.errors) {
            notification.error({
              title: t("jobs.errors.saving", {
                error: JSON.stringify(!result2.errors)
              })
            });
            return;
          }
        }

        form.resetFields();
        form.resetFields();
        history(`/manage/courtesycars/contracts/${result.data.insert_cccontracts.returning[0].id}`);
      } else {
        notification.error({
          title: t("contracts.errors.saving", {
            error: JSON.stringify(!result.errors)
          })
        });
      }
    } else {
      notification.error({
        title: t("contracts.errors.selectjobandcar")
      });
    }
    setLoading(false);
  };

  useEffect(() => {
    document.title = t("titles.contracts-create", {
      app: InstanceRenderManager({
        imex: "$t(titles.imexonline)",
        rome: "$t(titles.romeonline)"
      })
    });
    setSelectedHeader("newcontract");
    setBreadcrumbs([
      { link: "/manage/courtesycars", label: t("titles.bc.courtesycars") },
      {
        link: "/manage/courtesycars/contracts",
        label: t("titles.bc.contracts")
      },
      {
        link: "/manage/courtesycars/contracts/new",
        label: t("titles.bc.contracts-create")
      }
    ]);
  }, [t, setBreadcrumbs, setSelectedHeader]);

  return (
    <FeatureWrapperComponent
      featureName="courtesycars"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().courtesycars.general} />
        </Card>
      }
    >
      <RbacWrapper action="contracts:create">
        <Form form={form} layout="vertical" autoComplete="no" onFinish={handleFinish}>
          <ContractCreatePageComponent
            loading={loading}
            form={form}
            selectedJobState={selectedJobState}
            selectedCarState={selectedCarState}
          />
        </Form>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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