import { Button } from "antd";
import { useTranslation } from "react-i18next";
import { useMutation } from "@apollo/client/react";
import { UPDATE_JOBS } from "../../graphql/jobs.queries";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function OwnerDetailUpdateJobsComponent({ owner, selectedJobs, disabled }) {
  const { t } = useTranslation();
  const [updateJobs] = useMutation(UPDATE_JOBS);
  const notification = useNotification();

  const handlecClick = () => {
    logImEXEvent("owner_update_jobs", { count: selectedJobs.length });

    updateJobs({
      variables: {
        jobIds: selectedJobs,
        fields: {
          ownr_addr1: owner["ownr_addr1"],
          ownr_addr2: owner["ownr_addr2"],
          ownr_co_nm: owner["ownr_co_nm"],
          ownr_city: owner["ownr_city"],
          ownr_ctry: owner["ownr_ctry"],
          ownr_ea: owner["ownr_ea"],
          ownr_fn: owner["ownr_fn"],
          ownr_ph1: owner["ownr_ph1"],
          ownr_ph1_ty: owner["ownr_ph1_ty"],
          ownr_ln: owner["ownr_ln"],
          ownr_ph2: owner["ownr_ph2"],
          ownr_ph2_ty: owner["ownr_ph2_ty"],
          ownr_st: owner["ownr_st"],
          ownr_title: owner["ownr_title"],
          ownr_zip: owner["ownr_zip"]
        }
      }
    })
      .then(() => {
        notification.success({ title: t("jobs.successes.updated") });
      })
      .catch((error) => {
        notification.error({
          title: t("jobs.errors.updating", { error: JSON.stringify(error) })
        });
      });
  };

  return (
    <Button disabled={disabled} onClick={handlecClick}>
      {t("owners.actions.update")}
    </Button>
  );
}
