import { useMutation } from "@apollo/client";
import { Button } from "antd";
import React, { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import queryString from "query-string";
import { useLocation, useNavigate } from "react-router-dom";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function ProductionRemoveButton({ jobId }) {
  const [removeJobFromProduction] = useMutation(UPDATE_JOB);
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const search = queryString.parse(useLocation().search);
  const history = useNavigate();
  const notification = useNotification();

  const handleRemoveFromProd = async () => {
    logImEXEvent("production_remove_job");
    setLoading(true);
    const result = await removeJobFromProduction({
      variables: { jobId: jobId, job: { inproduction: false } }
    });

    if (!!!result.errors) {
      notification["success"]({ message: t("production.successes.removed") });
      delete search.selected;
      history({ search: queryString.stringify(search) });
    } else {
      notification["error"]({
        message: t("production.errors.removing", {
          error: JSON.stringify(result.errors)
        })
      });
    }

    setLoading(false);
  };

  return (
    <Button loading={loading} onClick={handleRemoveFromProd} type={"danger"}>
      {t("production.actions.remove")}
    </Button>
  );
}
