import { useQuery } from "@apollo/client";
import React from "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";

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

export function EmailDocumentsComponent({
  emailConfig,
  form,
  selectedMediaState,
  bodyshop,
}) {
  const { t } = useTranslation();

  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 message={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}
      {!bodyshop.uselocalmediaserver && data && (
        <JobDocumentsGalleryExternal
          data={data ? data.documents : []}
          externalMediaState={[selectedMedia, setSelectedMedia]}
        />
      )}
      {bodyshop.uselocalmediaserver && (
        <JobsDocumentsLocalGalleryExternalComponent
          externalMediaState={[selectedMedia, setSelectedMedia]}
          jobId={emailConfig.jobid}
        />
      )}
    </div>
  );
}
