import { Button, Space } from "antd";
import axios from "axios";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { logImEXEvent } from "../../firebase/firebase.utils";
import formatBytes from "../../utils/formatbytes";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});

/*
################################################################################################
 Developer Note:
 Known Technical Debt Item
         Modifications to this code requires complementary changes to the Cloudinary code. Cloudinary code will be removed upon completed migration.
################################################################################################
*/

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

export function JobsDocumentsImgproxyDownloadButton({ galleryImages, identifier, jobId }) {
  const { t } = useTranslation();
  const [download, setDownload] = useState(null);
  const [loading, setLoading] = useState(false);

  const imagesToDownload = [
    ...galleryImages.images.filter((image) => image.isSelected),
    ...galleryImages.other.filter((image) => image.isSelected)
  ];

  const downloadProgress = ({ loaded }) => {
    setDownload((currentDownloadState) => ({
      downloaded: loaded ?? 0,
      speed: (loaded ?? 0) - (currentDownloadState?.downloaded ?? 0)
    }));
  };

  const standardMediaDownload = (bufferData) => {
    try {
      const a = document.createElement("a");
      const url = window.URL.createObjectURL(new Blob([bufferData]));
      a.href = url;
      a.download = `${identifier || "documents"}.zip`;
      a.click();
    } catch {
      setLoading(false);
      setDownload(null);
    }
  };

  const handleDownload = async () => {
    logImEXEvent("jobs_documents_download");
    setLoading(true);
    try {
      const { data } = await axios({
        url: "/media/imgproxy/download",
        method: "POST",
        responseType: "blob",
        data: { jobId, documentids: imagesToDownload.map((_) => _.id) },
        onDownloadProgress: downloadProgress
      });
      // Use the response data (Blob) to trigger download
      standardMediaDownload(data);
    } catch {
      // handle error (optional)
    } finally {
      setLoading(false);
      setDownload(null);
    }
  };

  return (
    <Button loading={download || loading} disabled={imagesToDownload.length < 1} onClick={handleDownload}>
      <Space>
        <span>{t("documents.actions.download")}</span>
        {download && <span>{`(${formatBytes(download.downloaded)} @ ${formatBytes(download.speed)} / second)`}</span>}
      </Space>
    </Button>
  );
}
