import { useMutation } from "@apollo/client";
import { Form, notification } from "antd";
import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { useHistory, useLocation } from "react-router-dom";
import { createStructuredSelector } from "reselect";
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 ContractCreatePageComponent from "./contract-create.page.component";

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 = useHistory();
  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 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.
        notification["success"]({
          message: 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"]({
              message: t("jobs.errors.saving", {
                error: JSON.stringify(!result2.errors),
              }),
            });
            return;
          }
        }

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

  useEffect(() => {
    document.title = t("titles.contracts-create");
    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 (
    <RbacWrapper action="contracts:create">
      <Form
        form={form}
        layout="vertical"
        autoComplete="no"
        onFinish={handleFinish}
      >
        <ContractCreatePageComponent
          loading={loading}
          form={form}
          selectedJobState={selectedJobState}
          selectedCarState={selectedCarState}
        />
      </Form>
    </RbacWrapper>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ContractCreatePageContainer);
