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

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

export function BillFormContainer({ bodyshop, form, billEdit, disabled, disableInvNumber }) {
  const {
    treatments: { Simple_Inventory }
  } = useSplitTreatments({
    attributes: {},
    names: ["Simple_Inventory"],
    splitKey: 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}
        preferredMake={lineData ? lineData.jobs_by_pk.v_make_desc : null}
      />
      {!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);
