import { useState } from "react";
import { Button, Form, Popconfirm } from "antd";
import { PageHeader } from "@ant-design/pro-layout";
import { useMutation } from "@apollo/client";
import VehicleDetailFormComponent from "./vehicle-detail-form.component";
import { useTranslation } from "react-i18next";
import dayjs from "../../utils/day";
import { DELETE_VEHICLE, UPDATE_VEHICLE } from "../../graphql/vehicles.queries";
import { useNavigate } from "react-router-dom";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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 = useNavigate();
  const notification = useNotification();

  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", {
          error: JSON.stringify(result.errors)
        })
      });
      setLoading(false);
    } else {
      notification["success"]({
        message: t("vehicles.successes.delete")
      });
      setLoading(false);
      history(`/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
            key="delete"
            trigger="click"
            onConfirm={handleDelete}
            disabled={vehicle.jobs.length !== 0}
            title={t("vehicles.labels.deleteconfirm")}
          >
            <Button type="primary" danger loading={loading} disabled={vehicle.jobs.length !== 0}>
              {t("general.actions.delete")}
            </Button>
          </Popconfirm>,
          <Button key="save" 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 ? dayjs(vehicle.v_prod_dt) : null
        }}
      >
        <VehicleDetailFormComponent form={form} loading={loading} />
      </Form>
    </>
  );
}

export default VehicleDetailFormContainer;
