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 } 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";

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 = useHistory();

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

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

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

  return (
    <RbacWrapper action="courtesycar:create">
      <Form
        form={form}
        autoComplete="new-password"
        onFinish={handleFinish}
        layout="vertical"
      >
        <CourtesyCarFormComponent form={form} saveLoading={loading} />
      </Form>
    </RbacWrapper>
  );
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(CourtesyCarCreateContainer);
