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

import { connect } from "react-redux";
import { createStructuredSelector } from "reselect";
import { selectBodyshop } 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";
import { useNotification } from "../../contexts/Notifications/notificationContext.jsx";

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

export function DocumentsLocalUploadComponent({
  children,
  bodyshop,
  job,
  vendorid,
  invoice_number,
  callbackAfterUpload,
  allowAllTypes
}) {
  const [fileList, setFileList] = useState([]);
  const { t } = useTranslation();
  const notification = useNotification();

  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
          },
          notification
        })
      }
      {...(!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);
