import { useQuery } from "@apollo/client/react";
import { useTranslation } from "react-i18next";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { GET_DOCUMENTS_BY_JOB } from "../../graphql/documents.queries";
import { selectEmailConfig } from "../../redux/email/email.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import JobDocumentsGalleryExternal from "../jobs-documents-gallery/jobs-documents-gallery.external.component";
import JobsDocumentsLocalGalleryExternalComponent from "../jobs-documents-local-gallery/jobs-documents-local-gallery.external.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import JobsDocumentImgproxyGalleryExternal from "../jobs-documents-imgproxy-gallery/jobs-documents-imgproxy-gallery.external.component";

const mapStateToProps = createStructuredSelector({
  //currentUser: selectCurrentUser
  bodyshop: selectBodyshop,
  emailConfig: selectEmailConfig
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(EmailDocumentsComponent);

export function EmailDocumentsComponent({ emailConfig, form, selectedMediaState, bodyshop }) {
  const { t } = useTranslation();
  const {
    treatments: { Imgproxy }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Imgproxy"],
    splitKey: bodyshop?.imexshopid
  });

  const [selectedMedia, setSelectedMedia] = selectedMediaState;
  const { loading, error, data } = useQuery(GET_DOCUMENTS_BY_JOB, {
    variables: {
      jobId: emailConfig.jobid
    },
    skip: !emailConfig.jobid,
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only"
  });

  return (
    <div>
      {loading && <LoadingSpinner />}
      {error && <AlertComponent title={error.message} type="error" />}
      {selectedMedia.filter((s) => s.isSelected).length >= 10 ? (
        <div style={{ color: "red" }}>{t("messaging.labels.maxtenimages")}</div>
      ) : null}
      {selectedMedia &&
      selectedMedia.filter((s) => s.isSelected).reduce((acc, val) => (acc = acc + val.size), 0) >=
        10485760 - new Blob([form.getFieldValue("html")]).size ? (
        <div style={{ color: "red" }}>{t("general.errors.sizelimit")}</div>
      ) : null}

      {Imgproxy.treatment === "on" ? (
        <>
          {!bodyshop.uselocalmediaserver && data && (
            <JobsDocumentImgproxyGalleryExternal
              jobId={emailConfig.jobid}
              externalMediaState={[selectedMedia, setSelectedMedia]}
            />
          )}
          {bodyshop.uselocalmediaserver && (
            <JobsDocumentsLocalGalleryExternalComponent
              externalMediaState={[selectedMedia, setSelectedMedia]}
              jobId={emailConfig.jobid}
              context="email"
            />
          )}
        </>
      ) : (
        <>
          {!bodyshop.uselocalmediaserver && data && (
            <JobDocumentsGalleryExternal
              data={data ? data.documents : []}
              externalMediaState={[selectedMedia, setSelectedMedia]}
            />
          )}
          {bodyshop.uselocalmediaserver && (
            <JobsDocumentsLocalGalleryExternalComponent
              externalMediaState={[selectedMedia, setSelectedMedia]}
              jobId={emailConfig.jobid}
              context="email"
            />
          )}
        </>
      )}
    </div>
  );
}
