import React, { useState } from "react";
import { Button, Form, notification, PageHeader, Popconfirm } from "antd";
import { useMutation } from "@apollo/client";
import VehicleDetailFormComponent from "./vehicle-detail-form.component";
import { useTranslation } from "react-i18next";
import moment from "moment";
import { DELETE_VEHICLE, UPDATE_VEHICLE } from "../../graphql/vehicles.queries";
import { useHistory } from "react-router-dom";

function VehicleDetailFormContainer({ vehicle, refetch }) {
  const { t } = useTranslation();
  const [updateVehicle] = useMutation(UPDATE_VEHICLE);
  const [deleteVehicle] = useMutation(DELETE_VEHICLE);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const history = useHistory();

  const handleDelete = async () => {
    setLoading(true);
    const result = await deleteVehicle({
      variables: { id: vehicle.id },
    });
    console.log(result);
    if (result.errors) {
      notification["error"]({
        message: t("vehicles.errors.deleting"),
      });
      setLoading(false);
    } else {
      notification["success"]({
        message: t("vehicles.successes.delete"),
      });
      setLoading(false);
      history.push(`/manage/vehicles`);
    }
  };

  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={[
          <Popconfirm
            trigger="click"
            onConfirm={handleDelete}
            disabled={vehicle.jobs.length !== 0}
            title={t("vehicles.labels.deleteconfirm")}
          >
            <Button
              type="danger"
              loading={loading}
              disabled={vehicle.jobs.length !== 0}
            >
              {t("general.actions.delete")}
            </Button>
          </Popconfirm>,
          <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;
