import { useMutation } from "@apollo/client/react";
import { Button, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { DELETE_DELIVERY_CHECKLIST, DELETE_INTAKE_CHECKLIST } from "../../graphql/jobs.queries";
import InstanceRenderManager from "../../utils/instanceRenderMgr";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function JobAdminDeleteIntake({ job }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const notification = useNotification();

  const [deleteIntake] = useMutation(DELETE_INTAKE_CHECKLIST);
  const [deleteDelivery] = useMutation(DELETE_DELIVERY_CHECKLIST);

  const handleDelete = async () => {
    setLoading(true);
    const result = await deleteIntake({
      variables: { jobId: job.id }
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
  };

  const handleDeleteDelivery = async () => {
    setLoading(true);
    const result = await deleteDelivery({
      variables: { jobId: job.id }
    });

    if (!result.errors) {
      notification.success({ title: t("jobs.successes.save") });
    } else {
      notification.error({
        title: t("jobs.errors.saving", {
          error: JSON.stringify(result.errors)
        })
      });
    }
    setLoading(false);
  };

  const InstanceRender = InstanceRenderManager({
    imex: true,
    rome: "USE_IMEX"
  });

  return InstanceRender ? (
    <Space wrap>
      <Button loading={loading} onClick={handleDelete} disabled={!job.intakechecklist}>
        {t("jobs.labels.deleteintake")}
      </Button>
      <Button loading={loading} onClick={handleDeleteDelivery} disabled={!job.deliverchecklist}>
        {t("jobs.labels.deletedelivery")}
      </Button>
    </Space>
  ) : null;
}
