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 { useNavigate } from "react-router-dom";
import { createStructuredSelector } from "reselect";
import CourtesyCarFormComponent from "../../components/courtesy-car-form/courtesy-car-form.component";
import RbacWrapper from "../../components/rbac-wrapper/rbac-wrapper.component";
import { INSERT_NEW_COURTESY_CAR } from "../../graphql/courtesy-car.queries";
import { setBreadcrumbs, setSelectedHeader } from "../../redux/application/application.actions";
import { selectBodyshop } from "../../redux/user/user.selectors";
import FeatureWrapperComponent from "../../components/feature-wrapper/feature-wrapper.component";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import UpsellComponent, { upsellEnum } from "../../components/upsell/upsell.component";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function CourtesyCarCreateContainer({ bodyshop, setBreadcrumbs, setSelectedHeader }) {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [insertCourtesyCar] = useMutation(INSERT_NEW_COURTESY_CAR);
  const { t } = useTranslation();
  const history = useNavigate();
  const notification = useNotification();

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await insertCourtesyCar({
      variables: { courtesycar: { ...values, bodyshopid: bodyshop.id } }
    });

    if (result.errors) {
      notification.error({
        title: t("courtesycars.errors.saving", {
          message: JSON.stringify(result.errors)
        })
      });
      setLoading(false);
    } else {
      setLoading(false);
      form.resetFields();
      form.resetFields();
      notification.success({ title: t("courtesycars.successes.saved") });
      history(`/manage/courtesycars/${result.data.insert_courtesycars.returning[0].id}`);
    }
  };

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

  return (
    <FeatureWrapperComponent
      featureName="courtesycars"
      noauth={
        <Card>
          <UpsellComponent upsell={upsellEnum().courtesycars.general} />
        </Card>
      }
    >
      <RbacWrapper action="courtesycar:create">
        <Form form={form} autoComplete="new-password" onFinish={handleFinish} layout="vertical">
          <CourtesyCarFormComponent form={form} saveLoading={loading} newCC={true} />
        </Form>
      </RbacWrapper>
    </FeatureWrapperComponent>
  );
}

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