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 moment from "moment";
import { UPDATE_VEHICLE } from "../../graphql/vehicles.queries";

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

  const handleFinish = values => {
    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();
    });
  };

  return (
    <Form
      onFinish={handleFinish}
      form={form}
      autoComplete="off"
      initialValues={{
        ...vehicle,
        v_prod_dt: vehicle.v_prod_dt ? moment(vehicle.v_prod_dt) : null
      }}
    >
      <VehicleDetailFormComponent />
    </Form>
  );
}

export default VehicleDetailFormContainer;
