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

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);
    logImEXEvent("vehicle_delete", {});
    const result = await deleteVehicle({
      variables: { id: vehicle.id }
    });
    console.log(result);
    if (result.errors) {
      notification.error({
        title: t("vehicles.errors.deleting", {
          error: JSON.stringify(result.errors)
        })
      });
      setLoading(false);
    } else {
      notification.success({
        title: t("vehicles.successes.delete")
      });
      setLoading(false);
      history(`/manage/vehicles`);
    }
  };

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

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

    notification.success({
      title: t("vehicles.successes.save")
    });

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

  return (
    <Card>
      <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>
    </Card>
  );
}

export default VehicleDetailFormContainer;
