import { useQuery } from "@apollo/client/react";
import { GET_DOCUMENTS_BY_JOB } from "../../graphql/documents.queries";
import AlertComponent from "../alert/alert.component";
import JobDocumentsImgProxy from "../jobs-documents-imgproxy-gallery/jobs-documents-imgproxy-gallery.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import JobDocuments from "./jobs-documents-gallery.component";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";

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

export default connect(mapStateToProps, mapDispatchToProps)(JobsDocumentsContainer);

/*
################################################################################################
 Developer Note:
 Known Technical Debt Item
         Modifications to this code requires complementary changes to the Imgproxy code. This code will be removed once the imgproxy migration is completed.
################################################################################################
*/
export function JobsDocumentsContainer({
  jobId,
  billId,
  documentsList,
  billsCallback,
  refetchOverride,
  ignoreSizeLimit,
  bodyshop
}) {
  const {
    treatments: { Imgproxy }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Imgproxy"],
    splitKey: bodyshop?.imexshopid
  });

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

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

  if (Imgproxy.treatment === "on") {
    return (
      <JobDocumentsImgProxy
        data={data?.documents || documentsList || []}
        downloadIdentifier={data && data.jobs_by_pk.ro_number}
        totalSize={data && data.documents_aggregate.aggregate.sum.size}
        billId={billId}
        jobId={jobId}
        refetch={refetchOverride || refetch}
        billsCallback={billsCallback}
        ignoreSizeLimit={ignoreSizeLimit}
      />
    );
  } else {
    return (
      <JobDocuments
        data={data?.documents || documentsList || []}
        downloadIdentifier={data && data.jobs_by_pk.ro_number}
        totalSize={data && data.documents_aggregate.aggregate.sum.size}
        billId={billId}
        jobId={jobId}
        refetch={refetchOverride || refetch}
        billsCallback={billsCallback}
        ignoreSizeLimit={ignoreSizeLimit}
      />
    );
  }
}
