import { useQuery } from "@apollo/client";
import queryString from "query-string";
import React from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { QUERY_BILLS_BY_JOBID } from "../../graphql/bills.queries";
import JobsDetailPliComponent from "./jobs-detail-pli.component";

export default function JobsDetailPliContainer({ job }) {
  const billsQuery = useQuery(QUERY_BILLS_BY_JOBID, {
    variables: { jobid: job.id },
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const search = queryString.parse(useLocation().search);
  const history = useNavigate();

  const handleBillOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.billid = record.id;
        history({ search: queryString.stringify(search) });
      }
    } else {
      delete search.billid;
      history({ search: queryString.stringify(search) });
    }
  };

  const handlePartsOrderOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.partsorderid = record.id;
        history({ search: queryString.stringify(search) });
      }
    } else {
      delete search.partsorderid;
      history({ search: queryString.stringify(search) });
    }
  };

  const handlePartsDispatchOnRowClick = (record) => {
    if (record) {
      if (record.id) {
        search.partsdispatchid = record.id;
        history.push({ search: queryString.stringify(search) });
      }
    } else {
      delete search.partsdispatchid;
      history.push({ search: queryString.stringify(search) });
    }
  };
  return (
    <JobsDetailPliComponent
      job={job}
      billsQuery={billsQuery}
      handleBillOnRowClick={handleBillOnRowClick}
      handlePartsOrderOnRowClick={handlePartsOrderOnRowClick}
      handlePartsDispatchOnRowClick={handlePartsDispatchOnRowClick}
    />
  );
}
