import React, { useState } from "react";
import { Button, Form, notification, PageHeader } from "antd";
import { useMutation } from "@apollo/client";
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 [loading, setLoading] = useState(false);

  const handleFinish = async (values) => {
    setLoading(true);
    const result = await updateVehicle({
      variables: { vehId: vehicle.id, vehicle: values },
    });

    if (!!result.errors) {
      notification["error"]({
        message: t("vehicles.errors.saving", {
          message: JSON.stringify(result.errors),
        }),
      });
    }

    notification["success"]({
      message: t("vehicles.successes.save"),
    });

    if (refetch) await refetch();
    form.resetFields();
    form.resetFields();
    setLoading(false);
  };

  return (
    <>
      <PageHeader
        title={t("menus.header.vehicles")}
        extra={
          <Button
            type="primary"
            loading={loading}
            onClick={() => form.submit()}
          >
            {t("general.actions.save")}
          </Button>
        }
      />
      <Form
        onFinish={handleFinish}
        form={form}
        autoComplete="off"
        layout="vertical"
        initialValues={{
          ...vehicle,
          v_prod_dt: vehicle.v_prod_dt ? moment(vehicle.v_prod_dt) : null,
        }}
      >
        <VehicleDetailFormComponent form={form} loading={loading} />
      </Form>
    </>
  );
}

export default VehicleDetailFormContainer;
