import { Button, Space } from "antd";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import cleanAxios from "../../utils/CleanAxios";
import formatBytes from "../../utils/formatbytes";
import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectAllMedia } from "../../redux/media/media.selectors";
import { selectBodyshop } from "../../redux/user/user.selectors";

const mapStateToProps = createStructuredSelector({
  bodyshop: selectBodyshop,
  allMedia: selectAllMedia
});
const mapDispatchToProps = () => ({
  //setUserLanguage: language => dispatch(setUserLanguage(language))
});
export default connect(mapStateToProps, mapDispatchToProps)(JobsLocalGalleryDownloadButton);

export function JobsLocalGalleryDownloadButton({ bodyshop, allMedia, job }) {
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [download, setDownload] = useState(false);

  const imagesToDownload = (allMedia?.[job.id] || []).filter((i) => i.isSelected);

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

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

  const handleDownload = async () => {
    const { localmediaserverhttp, localmediatoken } = bodyshop;
    const { id, ro_number } = job;
    setLoading(true);
    try {
      const response = await cleanAxios.post(
        `${localmediaserverhttp}/jobs/download`,
        {
          jobid: id,
          files: imagesToDownload.map((i) => i.filename)
        },
        {
          headers: { ims_token: localmediatoken },
          responseType: "arraybuffer",
          onDownloadProgress: downloadProgress
        }
      );
      standardMediaDownload(response.data, ro_number);
    } catch {
      // handle error (optional)
    } finally {
      setLoading(false);
      setDownload(null);
    }
  };

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