import { useLazyQuery } from "@apollo/client/react";
import { Button } from "antd";
import { useEffect } from "react";
import { useTranslation } from "react-i18next";
import { GET_JOB_FOR_CC_CONTRACT } from "../../graphql/jobs.queries";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

export default function ContractCreateJobPrefillComponent({ jobId, form }) {
  const [call, { loading, error, data }] = useLazyQuery(GET_JOB_FOR_CC_CONTRACT);
  const { t } = useTranslation();
  const notification = useNotification();

  const handleClick = () => {
    call({ variables: { id: jobId } });
  };

  useEffect(() => {
    if (data) {
      form.setFieldsValue({
        driver_dlst: data.jobs_by_pk.ownr_ast,
        driver_fn: data.jobs_by_pk.ownr_fn,
        driver_ln: data.jobs_by_pk.ownr_ln,
        driver_addr1: data.jobs_by_pk.ownr_addr1,
        driver_state: data.jobs_by_pk.ownr_st,
        driver_city: data.jobs_by_pk.ownr_city,
        driver_zip: data.jobs_by_pk.ownr_zip,
        driver_ph1: data.jobs_by_pk.ownr_ph1
      });
    }
  }, [data, form]);

  if (error) {
    notification.error({
      title: t("contracts.errors.fetchingjobinfo", {
        error: JSON.stringify(error)
      })
    });
  }

  return (
    <Button onClick={handleClick} disabled={!jobId} loading={loading}>
      {t("contracts.labels.populatefromjob")}
    </Button>
  );
}
