import { useQuery } from "@apollo/client/react";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_LINE_TICKET_BY_PK } from "../../graphql/jobs-lines.queries";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import LaborAllocationsTableComponent from "../labor-allocations-table/labor-allocations-table.component";
import PayrollLaborAllocationsTable from "../labor-allocations-table/labor-allocations-table.payroll.component";
import LoadingSkeleton from "../loading-skeleton/loading-skeleton.component";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({});
export default connect(mapStateToProps, mapDispatchToProps)(JobCloseRoGuardLabor);

export function JobCloseRoGuardLabor({ job, bodyshop, warningCallback }) {
  const jobId = job?.id ?? null;

  const { loading, error, data, refetch } = useQuery(GET_LINE_TICKET_BY_PK, {
    variables: { id: jobId },
    skip: !jobId,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  const {
    treatments: { Enhanced_Payroll }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Enhanced_Payroll"],
    splitKey: bodyshop.imexshopid
  });

  if (!jobId) return <LoadingSkeleton />;
  if (loading) return <LoadingSkeleton />;
  if (error) return <AlertComponent title={error.message} type="error" />;

  return Enhanced_Payroll.treatment === "on" ? (
    <PayrollLaborAllocationsTable
      jobId={jobId}
      timetickets={data ? data.timetickets : []}
      refetch={refetch}
      adjustments={data ? data.jobs_by_pk.lbr_adjustments : []}
      showWarning
      warningCallback={warningCallback}
    />
  ) : (
    <LaborAllocationsTableComponent
      jobId={jobId}
      joblines={data ? data.joblines : []}
      timetickets={data ? data.timetickets : []}
      refetch={refetch}
      adjustments={data ? data.jobs_by_pk.lbr_adjustments : []}
      showWarning
      warningCallback={warningCallback}
      disabled={true}
    />
  );
}
