import { useLazyQuery, useQuery } from "@apollo/client";
import React from "react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_JOB_LINES_TO_ENTER_BILL } from "../../graphql/jobs-lines.queries";
import { SEARCH_VENDOR_AUTOCOMPLETE } from "../../graphql/vendors.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import BillFormComponent from "./bill-form.component";
import BillCmdReturnsTableComponent from "../bill-cm-returns-table/bill-cm-returns-table.component";
import { QUERY_UNRECEIVED_LINES } from "../../graphql/parts-orders.queries";
import BillInventoryTable from "../bill-inventory-table/bill-inventory-table.component";
import { QUERY_OUTSTANDING_INVENTORY } from "../../graphql/inventory.queries";
import { useTreatments } from "@splitsoftware/splitio-react";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
});

export function BillFormContainer({
  bodyshop,
  form,
  billEdit,
  disabled,
  disableInvNumber,
}) {
  const { Simple_Inventory } = useTreatments(
    ["Simple_Inventory"],
    {},
    bodyshop && bodyshop.imexshopid
  );

  const { data: VendorAutoCompleteData } = useQuery(
    SEARCH_VENDOR_AUTOCOMPLETE,
    { fetchPolicy: "network-only", nextFetchPolicy: "network-only" }
  );

  const [loadLines, { data: lineData }] = useLazyQuery(
    GET_JOB_LINES_TO_ENTER_BILL
  );

  const [loadOutstandingReturns, { loading: returnLoading, data: returnData }] =
    useLazyQuery(QUERY_UNRECEIVED_LINES);
  const [loadInventory, { loading: inventoryLoading, data: inventoryData }] =
    useLazyQuery(QUERY_OUTSTANDING_INVENTORY);

  return (
    <>
      <BillFormComponent
        disabled={disabled}
        form={form}
        billEdit={billEdit}
        vendorAutoCompleteOptions={
          VendorAutoCompleteData && VendorAutoCompleteData.vendors
        }
        loadLines={loadLines}
        lineData={lineData ? lineData.joblines : []}
        job={lineData ? lineData.jobs_by_pk : null}
        responsibilityCenters={bodyshop.md_responsibility_centers || null}
        disableInvNumber={disableInvNumber}
        loadOutstandingReturns={loadOutstandingReturns}
        loadInventory={loadInventory}
      />
      {!billEdit && (
        <BillCmdReturnsTableComponent
          form={form}
          returnLoading={returnLoading}
          returnData={returnData}
        />
      )}
      {Simple_Inventory.treatment === "on" && (
        <BillInventoryTable
          form={form}
          inventoryLoading={inventoryLoading}
          inventoryData={billEdit ? [] : inventoryData}
          billEdit={billEdit}
        />
      )}
    </>
  );
}
export default connect(mapStateToProps, null)(BillFormContainer);
