import { PictureFilled } from "@ant-design/icons";
import { useQuery } from "@apollo/client/react";
import { useTreatmentsWithConfig } from "@splitsoftware/splitio-react";
import { Badge, Popover } from "antd";
import { useEffect, useState } 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 { selectBodyshop } from "../../redux/user/user.selectors";
import AlertComponent from "../alert/alert.component";
import JobDocumentsGalleryExternal from "../jobs-documents-gallery/jobs-documents-gallery.external.component";
import JobsDocumentImgproxyGalleryExternal from "../jobs-documents-imgproxy-gallery/jobs-documents-imgproxy-gallery.external.component";
import JobDocumentsLocalGalleryExternal from "../jobs-documents-local-gallery/jobs-documents-local-gallery.external.component";
import LoadingSpinner from "../loading-spinner/loading-spinner.component";
import "./chat-media-selector.styles.scss";

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

const mapDispatchToProps = () => ({});

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

export function ChatMediaSelector({ bodyshop, selectedMedia, setSelectedMedia, conversation }) {
  const { t } = useTranslation();
  const [open, setOpen] = useState(false);
  const {
    treatments: { Imgproxy }
  } = useTreatmentsWithConfig({
    attributes: {},
    names: ["Imgproxy"],
    splitKey: bodyshop && bodyshop.imexshopid
  });

  const { loading, error, data } = useQuery(GET_DOCUMENTS_BY_JOB, {
    fetchPolicy: "network-only",
    nextFetchPolicy: "network-only",
    variables: {
      jobId: conversation.job_conversations[0]?.jobid
    },
    skip:
      !open ||
      !conversation.job_conversations ||
      conversation.job_conversations.length === 0 ||
      bodyshop.uselocalmediaserver
  });

  const handleVisibleChange = (change) => {
    setOpen(change);
  };

  useEffect(() => {
    // Instead of wiping the array (which holds media objects), just clear selection flags
    setSelectedMedia((prev) => prev.map((m) => ({ ...m, isSelected: false })));
  }, [setSelectedMedia, conversation]);

  //Knowingly taking on the technical debt of poor implementation below. Done this way to avoid an edge case where no component may be displayed.
  //Cloudinary will be removed once the migration is completed.
  //If Imageproxy is on, rely only on the LMS selector
  //If not on, use the old methods.
  const content = (
    <div className="media-selector-content">
      {loading && <LoadingSpinner />}
      {error && <AlertComponent title={error.message} type="error" />}
      {selectedMedia.filter((s) => s.isSelected).length >= 10 ? (
        <div className="error-message">{t("messaging.labels.maxtenimages")}</div>
      ) : null}

      {Imgproxy.treatment === "on" ? (
        <>
          {!bodyshop.uselocalmediaserver && (
            <JobsDocumentImgproxyGalleryExternal
              jobId={conversation.job_conversations[0]?.jobid}
              externalMediaState={[selectedMedia, setSelectedMedia]}
            />
          )}
          {bodyshop.uselocalmediaserver && open && (
            <JobDocumentsLocalGalleryExternal
              externalMediaState={[selectedMedia, setSelectedMedia]}
              jobId={conversation.job_conversations[0]?.jobid}
              context="chat"
            />
          )}
        </>
      ) : (
        <>
          {!bodyshop.uselocalmediaserver && data && (
            <JobDocumentsGalleryExternal
              data={data ? data.documents : []}
              externalMediaState={[selectedMedia, setSelectedMedia]}
            />
          )}
          {bodyshop.uselocalmediaserver && open && (
            <JobDocumentsLocalGalleryExternal
              externalMediaState={[selectedMedia, setSelectedMedia]}
              jobId={conversation.job_conversations[0]?.jobid}
              context="chat"
            />
          )}
        </>
      )}
    </div>
  );

  return (
    <Popover
      content={
        conversation.job_conversations.length === 0 ? (
          <div className="no-jobs-message">{t("messaging.errors.noattachedjobs")}</div>
        ) : (
          content
        )
      }
      title={t("messaging.labels.selectmedia")}
      trigger="click"
      open={open}
      onOpenChange={handleVisibleChange}
      destroyOnHidden
      classNames={{ root: "media-selector-popover" }}
    >
      <Badge count={selectedMedia.filter((s) => s.isSelected).length}>
        <PictureFilled style={{ margin: "0 .5rem" }} />
      </Badge>
    </Popover>
  );
}
