import React from "react";
import { Form, notification } from "antd";
import { useMutation } from "react-apollo";
import VehicleDetailFormComponent from "./vehicle-detail-form.component";
import { useTranslation } from "react-i18next";
import { UPDATE_VEHICLE } from "../../graphql/vehicles.queries";

function VehicleDetailFormContainer({ form, vehicle, refetch }) {
  const { t } = useTranslation();
  const [updateVehicle] = useMutation(UPDATE_VEHICLE);

  const handleSubmit = e => {
    e.preventDefault();

    form.validateFieldsAndScroll((err, values) => {
      if (err) {
        notification["error"]({
          message: t("vehicles.errors.validationtitle"),
          description: t("vehicles.errors.validation")
        });
      }
      if (!err) {
        updateVehicle({
          variables: { vehId: vehicle.id, vehicle: values }
        }).then(r => {
          notification["success"]({
            message: t("vehicles.successes.save")
          });
          //TODO Better way to reset the field decorators?
          if (refetch) refetch().then();
          form.resetFields();
        });
      }
    });
  };

  return (
    <Form onSubmit={handleSubmit} autoComplete="off">
      <VehicleDetailFormComponent form={form} vehicle={vehicle} />
    </Form>
  );
}

export default Form.create({ name: "VehicleDetailFormContainer" })(
  VehicleDetailFormContainer
);
