import { UploadOutlined } from "@ant-design/icons";
import { Upload } from "antd";
import React, { useState } from "react";

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop, selectCurrentUser } from "../../redux/user/user.selectors";
import { handleUpload } from "./documents-local-upload.utility";
import { HasFeatureAccess } from "../feature-wrapper/feature-wrapper.component";
import LockWrapperComponent from "../lock-wrapper/lock-wrapper.component";
import { useTranslation } from "react-i18next";

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

export function DocumentsLocalUploadComponent({
  children,
  currentUser,
  bodyshop,
  job,
  vendorid,
  invoice_number,
  callbackAfterUpload,
  allowAllTypes
}) {
  const [fileList, setFileList] = useState([]);
  const { t } = useTranslation();
  const handleDone = (uid) => {
    setTimeout(() => {
      setFileList((fileList) => fileList.filter((x) => x.uid !== uid));
    }, 2000);
  };

  const hasMediaAccess = HasFeatureAccess({ bodyshop, featureName: "media" });

  return (
    <Upload.Dragger
      multiple={true}
      fileList={fileList}
      disabled={!hasMediaAccess}
      onChange={(f) => {
        if (f.event && f.event.percent === 100) handleDone(f.file.uid);

        setFileList(f.fileList);
      }}
      customRequest={(ev) =>
        handleUpload({
          ev,
          context: {
            jobid: job.id,
            vendorid,
            invoice_number,
            callback: callbackAfterUpload
          }
        })
      }
      {...(!allowAllTypes && {
        accept: "audio/*, video/*, image/*, .pdf, .doc, .docx, .xls, .xlsx"
      })}
    >
      {children || (
        <>
          <p className="ant-upload-drag-icon">
            <UploadOutlined />
          </p>
          <p className="ant-upload-text">
            <LockWrapperComponent featureName="media">{t("documents.labels.dragtoupload")}</LockWrapperComponent>
          </p>
        </>
      )}
    </Upload.Dragger>
  );
}

export default connect(mapStateToProps, null)(DocumentsLocalUploadComponent);
