import { useMutation } from "@apollo/client/react";
import { Checkbox, Space, Spin } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { UPDATE_JOB } from "../../graphql/jobs.queries";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";
import { logImEXEvent } from "../../firebase/firebase.utils.js";

export default function JobRemoveFromPartsQueue({ checked, jobId }) {
  const [updateJob] = useMutation(UPDATE_JOB);
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const notification = useNotification();

  const handleChange = async (e) => {
    setLoading(true);
    logImEXEvent("parts_queue_toggle", { estimators: e });

    const result = await updateJob({
      variables: { jobId: jobId, job: { queued_for_parts: e.target.checked } }
    });

    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);
  };

  return (
    <Space>
      <Checkbox checked={checked} onChange={handleChange} />
      {loading && <Spin size="small" />}
    </Space>
  );
}
