import { isNotPresent, findBy, isNotEmpty, noop } from '@bigbinary/neeto-cist';
import { assoc, isEmpty, isNotNil } from 'ramda';
import { globalProps } from '@bigbinary/neeto-commons-frontend/initializers';
import _defineProperty from '@babel/runtime/helpers/defineProperty';
import classnames from 'classnames';
import FileUpload$1 from '@bigbinary/neeto-icons/FileUpload';
import { useTranslation } from 'react-i18next';
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import path from 'path';
import { t } from 'i18next';
import { n } from './inject-css-C2dztUxs.js';
import FileGeneric from '@bigbinary/neeto-icons/FileGeneric';
import Check from '@bigbinary/neeto-icons/Check';
import Close from '@bigbinary/neeto-icons/Close';
import { motion } from 'framer-motion';
import _toConsumableArray from '@babel/runtime/helpers/toConsumableArray';
import _asyncToGenerator from '@babel/runtime/helpers/asyncToGenerator';
import _slicedToArray from '@babel/runtime/helpers/slicedToArray';
import { useState, useRef, useCallback, useEffect, createElement } from 'react';
import { DirectUpload } from '@rails/activestorage';
import { useDropzone } from 'react-dropzone';
import _objectWithoutProperties from '@babel/runtime/helpers/objectWithoutProperties';
import { useField } from 'formik';

var FILE_MIME_TYPES = {
  pdf: ["application/pdf"],
  doc: ["application/msword", "application/wps-writer"],
  docx: ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
  xls: ["application/vnd.ms-excel"],
  xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
  csv: ["text/csv"],
  txt: ["text/plain"],
  rtf: ["application/rtf", "text/rtf"],
  html: ["text/html"],
  htm: ["text/html"],
  md: ["text/markdown", "text/x-markdown"],
  zip: ["application/zip"],
  mp3: ["audio/mpeg"],
  wma: ["audio/x-ms-wma", "video/x-ms-asf"],
  mp4: ["video/mp4"],
  mpg: ["video/mpeg"],
  mpeg: ["video/mpeg"],
  flv: ["video/x-flv"],
  avi: ["video/x-msvideo"],
  jpg: ["image/jpeg"],
  jpeg: ["image/jpeg"],
  png: ["image/png"],
  gif: ["image/gif"],
  json: ["application/json"],
  epub: ["application/epub+zip"],
  aac: ["audio/aac"],
  svg: ["image/svg+xml"],
  ico: ["image/vnd.microsoft.icon"]
};
var ERROR_CODES = {
  FILE_TOO_LARGE: "file-too-large",
  FILE_INVALID_TYPE: "file-invalid-type",
  TOO_MANY_FILES: "too-many-files"
};
var DIRECT_UPLOAD_URL = "/api/direct_uploads";
var MAX_FILE_SIZE = (globalProps === null || globalProps === void 0 ? void 0 : globalProps.endUserUploadedFileSizeLimitInMb) || 10;

function ownKeys$2(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$2(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$2(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$2(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var DropZone = function DropZone(_ref) {
  var isDragActive = _ref.isDragActive,
    getRootProps = _ref.getRootProps,
    getInputProps = _ref.getInputProps,
    multipleFilesAllowed = _ref.multipleFilesAllowed,
    maxFileSize = _ref.maxFileSize,
    allowedFileTypes = _ref.allowedFileTypes,
    hasFileSizeLimit = _ref.hasFileSizeLimit;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var shouldAllowSingleFileUpload = !multipleFilesAllowed;
  var shouldShowFileSizeLimit = hasFileSizeLimit && maxFileSize;
  return /*#__PURE__*/jsx("div", _objectSpread$2(_objectSpread$2({}, getRootProps({
    className: classnames(["neeto-molecules-file-upload__dropzone"], {
      "neeto-molecules-file-upload__dropzone--drag-active": isDragActive
    })
  })), {}, {
    children: /*#__PURE__*/jsxs("div", {
      className: "neeto-molecules-file-upload__dropzone-inner",
      "data-cy": "file-upload-body",
      "data-testid": "file-upload-body",
      children: [/*#__PURE__*/jsx(FileUpload$1, {
        className: "neeto-molecules-file-upload__upload-icon",
        size: "36"
      }), /*#__PURE__*/jsxs("div", {
        className: "neeto-molecules-file-upload__dropzone-content",
        children: [/*#__PURE__*/jsxs("label", {
          className: "neeto-molecules-file-upload__upload-label",
          htmlFor: "file-upload",
          children: [/*#__PURE__*/jsx("span", {
            className: "neeto-molecules-file-upload__choose-file",
            children: t("neetoMolecules.fileUpload.filesDropzone.chooseFileOrDragHere")
          }), /*#__PURE__*/jsx("input", _objectSpread$2(_objectSpread$2({}, getInputProps()), {}, {
            "data-cy": "image-browse-button"
          }))]
        }), /*#__PURE__*/jsxs("div", {
          className: "neeto-molecules-file-upload__dropzone-helper-block",
          children: [shouldAllowSingleFileUpload && /*#__PURE__*/jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-cy": "upload-only-one-file-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.oneFileAllowed")
          }), shouldShowFileSizeLimit && /*#__PURE__*/jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-cy": "maximum-allowed-size-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.maxFileSize", {
              size: maxFileSize,
              unit: "MB"
            })
          }), allowedFileTypes && /*#__PURE__*/jsx("p", {
            className: "neeto-molecules-file-upload__dropzone-helper-text",
            "data-cy": "allowed-files-types-text",
            children: t("neetoMolecules.fileUpload.filesDropzone.allowedFileTypes", {
              types: allowedFileTypes
            })
          })]
        })]
      })]
    })
  }));
};

var getAcceptedFileTypes = function getAcceptedFileTypes(allowedFileTypes) {
  var accepted = {};
  allowedFileTypes.split(", ").forEach(function (type) {
    var mimeTypes = FILE_MIME_TYPES[type] || ["application/octet-stream"];
    var extension = ".".concat(type);
    if (isNotPresent(type) || isNotPresent(mimeTypes)) return;
    mimeTypes.forEach(function (mimeType) {
      if (accepted[mimeType]) accepted[mimeType].push(extension);else accepted[mimeType] = [extension];
    });
  });
  return accepted;
};
var convertBytesToMb = function convertBytesToMb(bytes) {
  return ((bytes - 10) / (1028 * 1024)).toFixed(2);
};
var renderErrorMessage = function renderErrorMessage(errorObject, maxFileSize, isMultiple) {
  var error = errorObject.errors[0];
  var file = errorObject.file;
  if (error) {
    var code = error.code;
    if (code === ERROR_CODES.FILE_TOO_LARGE) {
      return t("neetoMolecules.fileUpload.filesDropzone.errors.fileTooLarge", {
        fileName: file.name,
        maxSize: "".concat(Math.round(maxFileSize / 1048576), "MB")
      });
    } else if (code === ERROR_CODES.FILE_INVALID_TYPE) {
      return t("neetoMolecules.fileUpload.filesDropzone.errors.fileInvalidType", {
        fileType: path.extname(file.name)
      });
    } else if (code === ERROR_CODES.TOO_MANY_FILES && !isMultiple) {
      return t("neetoMolecules.fileUpload.filesDropzone.errors.tooManyFiles", {
        maxFiles: 1
      });
    }
  }
  return t("neetoMolecules.fileUpload.filesDropzone.errors.defaultError", {
    fileName: file.name
  });
};
var convertMbToBytes = function convertMbToBytes(mb) {
  return mb * 1028 * 1024 + 10;
};

var ErrorMessages = function ErrorMessages(_ref) {
  var fileRejections = _ref.fileRejections,
    maxFileSizeInBytes = _ref.maxFileSizeInBytes;
  var _useTranslation = useTranslation(),
    t = _useTranslation.t;
  var hasMultipleFileErrors = fileRejections.some(function (_ref2) {
    var errors = _ref2.errors;
    return errors[0].code === ERROR_CODES.TOO_MANY_FILES;
  });
  return /*#__PURE__*/jsxs(Fragment, {
    children: [hasMultipleFileErrors && /*#__PURE__*/jsx("p", {
      className: "neeto-molecules-input__error-text",
      "data-cy": "form-file-upload-input-error",
      children: /*#__PURE__*/jsx("span", {
        className: "neeto-molecules-input__error-text-style-handle",
        children: t("neetoMolecules.fileUpload.filesDropzone.errors.tooManyFiles", {
          maxFiles: 1
        })
      })
    }), fileRejections.filter(function (_ref3) {
      var errors = _ref3.errors;
      return errors[0].code !== ERROR_CODES.TOO_MANY_FILES;
    }).map(function (file, index) {
      return /*#__PURE__*/jsx("p", {
        className: "neeto-molecules-input__error-text",
        "data-cy": "form-file-upload-input-error",
        children: /*#__PURE__*/jsx("span", {
          className: "neeto-molecules-input__error-text-style-handle",
          children: renderErrorMessage(file, maxFileSizeInBytes, false)
        })
      }, index);
    })]
  });
};

var css = ".neeto-ui-theme--dark,.neeto-ui-theme--light,:root{--neeto-molecules-file-upload-dropzone-color:var(--neeto-ui-gray-800),1;--neeto-molecules-file-upload-dropzone-help-text-color:var(--neeto-ui-gray-700),1;--neeto-molecules-file-upload-dropzone-icon-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-dropzone-background-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-dropzone-hover-background-color:var(--neeto-ui-gray-100,1);--neeto-molecules-file-upload-dropzone-border-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-border-radius:var(--neeto-ui-rounded-md);--neeto-molecules-file-upload-transition:var(--neeto-ui-transition);--neeto-molecules-file-upload-list-item-border-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-list-item-background-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-preview-icon-color:var(--neeto-ui-gray-400),1;--neeto-molecules-file-upload-progress-ring-background-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-success-background-color:var(--neeto-ui-primary-500),1;--neeto-molecules-file-upload-success-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-cancel-background-color:var(--neeto-ui-error-500),1;--neeto-molecules-file-upload-cancel-color:var(--neeto-ui-white),1;--neeto-molecules-file-upload-error-color:var(--neeto-ui-error-500),1;--neeto-molecules-file-upload-error-background-color:var(--neeto-ui-white),1}.neeto-molecules-file-upload__dropzone{background-color:rgba(var(--neeto-molecules-file-upload-dropzone-background-color));border:2px dashed rgba(var(--neeto-molecules-file-upload-dropzone-border-color));border-radius:var(--neeto-molecules-file-upload-border-radius);color:rgba(var(--neeto-molecules-file-upload-dropzone-color));padding:1.5em;transition:var(--neeto-molecules-file-upload-transition)}.neeto-molecules-file-upload__dropzone:hover{background-color:rgba(var(--neeto-molecules-file-upload-dropzone-hover-background-color))}.neeto-molecules-file-upload__dropzone-inner{text-align:center}.neeto-molecules-file-upload__upload-icon{color:rgba(var(--neeto-molecules-file-upload-dropzone-icon-color));display:block;margin-bottom:1.25em;margin-left:auto;margin-right:auto}.neeto-molecules-file-upload__upload-label{display:flex;font-size:1rem;gap:.3125em;justify-content:center}.neeto-molecules-file-upload__choose-file{font-weight:500}.neeto-molecules-file-upload__dropzone-helper-block{margin-top:.5em}.neeto-molecules-file-upload__dropzone-helper-text{color:rgba(var(--neeto-molecules-file-upload-dropzone-help-text-color));display:block;font-size:.75rem;line-height:1.2;margin-bottom:.5rem}.neeto-molecules-file-upload__uploaded-list{list-style:none;margin:1.25em 0;padding:0}.neeto-molecules-file-upload__uploaded-list-item{align-items:center;background-color:rgba(var(--neeto-molecules-file-upload-list-item-background-color));border:1px solid rgba(var(--neeto-molecules-file-upload-list-item-border-color));display:flex;gap:.75em;list-style:none;margin-bottom:-.0625rem;padding:.5em .75em}.neeto-molecules-file-upload__uploaded-list-item:first-of-type{border-top-left-radius:var(--neeto-molecules-file-upload-border-radius);border-top-right-radius:var(--neeto-molecules-file-upload-border-radius)}.neeto-molecules-file-upload__uploaded-list-item:last-of-type{border-bottom-left-radius:var(--neeto-molecules-file-upload-border-radius);border-bottom-right-radius:var(--neeto-molecules-file-upload-border-radius)}.neeto-molecules-file-upload__file-preview{color:rgba(var(--neeto-molecules-file-upload-preview-icon-color));position:relative}.neeto-molecules-file-upload__file-preview .neeto-molecules-progress{align-items:center;display:flex;height:100%;justify-content:center;left:0;position:absolute;top:0;width:100%}.neeto-molecules-file-upload__file-preview .neeto-molecules-progress__circle-wrapper{color:rgba(var(--neeto-molecules-file-upload-progress-ring-background-color));position:relative}.neeto-molecules-file-upload__file-info{word-wrap:break-word;display:flex;flex-direction:column;flex-grow:1;min-width:0;overflow-wrap:break-word}.neeto-molecules-file-upload__file-info-name{font-size:.875em;margin-bottom:.3125em}.neeto-molecules-file-upload__file-info-size{color:rgba(var(--neeto-molecules-file-upload-dropzone-help-text-color));font-size:.75em}.neeto-molecules-file-upload__actions{flex-shrink:0;margin-left:auto;position:relative}.neeto-molecules-file-upload__success-indicator{align-items:center;border-radius:100%;display:inline-flex;height:1.75em;justify-content:center;width:1.75em}.neeto-molecules-file-upload__success-indicator.neeto-molecules-file-upload__success-indicator--active{background-color:rgba(var(--neeto-molecules-file-upload-success-background-color));color:rgba(var(--neeto-molecules-file-upload-success-color))}.neeto-molecules-file-upload__button--red{align-items:center;background-color:rgba(var(--neeto-molecules-file-upload-cancel-background-color));border-radius:100%;color:rgba(var(--neeto-molecules-file-upload-cancel-color));display:inline-flex;height:1.75em;justify-content:center;width:1.75em}.neeto-molecules-file-upload__remove-button{left:0;opacity:0;position:absolute;top:0;transition:var(--neeto-molecules-file-upload-transition);visibility:hidden}.neeto-molecules-file-upload__actions:hover .neeto-molecules-file-upload__remove-button{opacity:1;visibility:visible}.neeto-molecules-invisible{visibility:hidden}.neeto-molecules-input__error-text{font-size:.875rem;line-height:1.2;margin-top:.5em}.neeto-molecules-input__error-text-style-handle{background-color:rgba(var(--neeto-molecules-file-upload-error-background-color));border-radius:.1875rem;color:rgba(var(--neeto-molecules-file-upload-error-color));display:inline-block;font-size:.875rem;line-height:1.2;padding:.1875rem .375rem}";
n(css,{});

var Progress = function Progress(_ref) {
  var percents = _ref.percents,
    _ref$stroke = _ref.stroke,
    stroke = _ref$stroke === void 0 ? "currentColor" : _ref$stroke,
    _ref$emptyStroke = _ref.emptyStroke,
    emptyStroke = _ref$emptyStroke === void 0 ? stroke : _ref$emptyStroke,
    _ref$emptyStrokeOpaci = _ref.emptyStrokeOpacity,
    emptyStrokeOpacity = _ref$emptyStrokeOpaci === void 0 ? 0.25 : _ref$emptyStrokeOpaci,
    _ref$duration = _ref.duration,
    duration = _ref$duration === void 0 ? 0.5 : _ref$duration,
    _ref$delay = _ref.delay,
    delay = _ref$delay === void 0 ? 0 : _ref$delay,
    _ref$size = _ref.size,
    size = _ref$size === void 0 ? 100 : _ref$size,
    _ref$strokeWidth = _ref.strokeWidth,
    strokeWidth = _ref$strokeWidth === void 0 ? 12 : _ref$strokeWidth;
  var radius = 45;
  var circumference = Math.ceil(2 * Math.PI * radius);
  var fillPercents = Math.abs(Math.ceil(circumference / 100 * (percents - 100)));
  var transition = {
    duration: duration,
    delay: delay
  };
  var variants = {
    hidden: {
      strokeDashoffset: circumference,
      transition: transition
    },
    show: {
      strokeDashoffset: fillPercents,
      transition: transition
    }
  };
  return /*#__PURE__*/jsx("div", {
    className: "neeto-molecules-progress__circle",
    children: /*#__PURE__*/jsxs("div", {
      className: "neeto-molecules-progress__circle-wrapper",
      style: {
        height: size
      },
      children: [/*#__PURE__*/jsx("svg", {
        height: size,
        version: "1.1",
        viewBox: "0 0 100 100",
        width: size,
        xmlns: "http://www.w3.org/2000/svg",
        children: /*#__PURE__*/jsx("circle", {
          strokeWidth: strokeWidth,
          className: "circle",
          cx: "50",
          cy: "50",
          fill: "transparent",
          r: radius,
          stroke: emptyStroke,
          strokeOpacity: emptyStrokeOpacity
        })
      }), /*#__PURE__*/jsx("svg", {
        height: size,
        viewBox: "0 0 100 100",
        width: size,
        style: {
          position: "absolute",
          transform: "rotate(-90deg)",
          overflow: "visible",
          top: 0
        },
        children: /*#__PURE__*/jsx(motion.circle, {
          stroke: stroke,
          strokeWidth: strokeWidth,
          variants: variants,
          animate: "show",
          cx: "50",
          cy: "50",
          fill: "transparent",
          initial: "hidden",
          r: radius,
          strokeDasharray: circumference,
          strokeDashoffset: fillPercents
        })
      })]
    })
  });
};

var FilePreview = function FilePreview(_ref) {
  var file = _ref.file,
    isUploading = _ref.isUploading,
    cancel = _ref.cancel,
    progress = _ref.progress;
  return /*#__PURE__*/jsxs("li", {
    className: "neeto-molecules-file-upload__uploaded-list-item",
    children: [/*#__PURE__*/jsxs("div", {
      className: "neeto-molecules-file-upload__file-preview",
      children: [/*#__PURE__*/jsx("a", {
        className: classnames({
          "neeto-molecules-invisible": isUploading
        }),
        href: file.url,
        rel: "noreferrer",
        target: "_blank",
        children: /*#__PURE__*/jsx(FileGeneric, {})
      }), isUploading && /*#__PURE__*/jsx("div", {
        className: "neeto-molecules-progress",
        children: /*#__PURE__*/jsx(Progress, {
          percents: progress || 0,
          size: 20
        })
      })]
    }), /*#__PURE__*/jsxs("div", {
      className: "neeto-molecules-file-upload__file-info",
      children: [/*#__PURE__*/jsx("span", {
        className: "neeto-molecules-file-upload__file-info-name",
        "data-cy": "file-name",
        children: file.name
      }), /*#__PURE__*/jsx("span", {
        className: "neeto-molecules-file-upload__file-info-size",
        children: file.size ? "".concat(convertBytesToMb(file.size), " MB") : ""
      })]
    }), /*#__PURE__*/jsxs("div", {
      className: "neeto-molecules-file-upload__actions",
      children: [/*#__PURE__*/jsx("span", {
        className: classnames("neeto-molecules-file-upload__success-indicator", {
          "neeto-molecules-file-upload__success-indicator--active": file.url
        }),
        children: file.url && /*#__PURE__*/jsx(Check, {
          "data-cy": "file-upload-success"
        })
      }), /*#__PURE__*/jsx("button", {
        className: "neeto-molecules-file-upload__button--red neeto-molecules-file-upload__remove-button",
        type: "button",
        onClick: cancel,
        children: /*#__PURE__*/jsx(Close, {})
      })]
    })]
  }, file.url);
};

function _regenerator() { /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */ var e, t, r = "function" == typeof Symbol ? Symbol : {}, n = r.iterator || "@@iterator", o = r.toStringTag || "@@toStringTag"; function i(r, n, o, i) { var c = n && n.prototype instanceof Generator ? n : Generator, u = Object.create(c.prototype); return _regeneratorDefine2(u, "_invoke", function (r, n, o) { var i, c, u, f = 0, p = o || [], y = false, G = { p: 0, n: 0, v: e, a: d, f: d.bind(e, 4), d: function d(t, r) { return i = t, c = 0, u = e, G.n = r, a; } }; function d(r, n) { for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) { var o, i = p[t], d = G.p, l = i[2]; r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0)); } if (o || r > 1) return a; throw y = true, n; } return function (o, p, l) { if (f > 1) throw TypeError("Generator is already running"); for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) { i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u); try { if (f = 2, i) { if (c || (o = "next"), t = i[o]) { if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object"); if (!t.done) return t; u = t.value, c < 2 && (c = 0); } else 1 === c && (t = i["return"]) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1); i = e; } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break; } catch (t) { i = e, c = 1, u = t; } finally { f = 1; } } return { value: t, done: y }; }; }(r, o, i), true), u; } var a = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} t = Object.getPrototypeOf; var c = [][n] ? t(t([][n]())) : (_regeneratorDefine2(t = {}, n, function () { return this; }), t), u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c); function f(e) { return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine2(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e; } return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine2(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine2(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine2(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine2(u), _regeneratorDefine2(u, o, "Generator"), _regeneratorDefine2(u, n, function () { return this; }), _regeneratorDefine2(u, "toString", function () { return "[object Generator]"; }), (_regenerator = function _regenerator() { return { w: i, m: f }; })(); }
function _regeneratorDefine2(e, r, n, t) { var i = Object.defineProperty; try { i({}, "", {}); } catch (e) { i = 0; } _regeneratorDefine2 = function _regeneratorDefine(e, r, n, t) { function o(r, n) { _regeneratorDefine2(e, r, function (e) { return this._invoke(r, n, e); }); } r ? i ? i(e, r, { value: n, enumerable: !t, configurable: !t, writable: !t }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2)); }, _regeneratorDefine2(e, r, n, t); }
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var useFileUpload = function useFileUpload(_ref) {
  var disabled = _ref.disabled,
    accept = _ref.accept,
    multiple = _ref.multiple,
    maxFileSize = _ref.maxFileSize,
    minFileSize = _ref.minFileSize,
    files = _ref.files,
    onChange = _ref.onChange,
    setError = _ref.setError,
    setTouched = _ref.setTouched,
    hasFileSizeLimit = _ref.hasFileSizeLimit;
  var _useState = useState({}),
    _useState2 = _slicedToArray(_useState, 2),
    uploadProgress = _useState2[0],
    setUploadProgress = _useState2[1];
  var _useState3 = useState(""),
    _useState4 = _slicedToArray(_useState3, 2),
    uploadError = _useState4[0],
    setUploadError = _useState4[1];
  var filesRef = useRef(files);
  filesRef.current = files;
  var cancel = useCallback(function (index) {
    return function () {
      setUploadProgress(assoc(files[index].name, null));
      var newFiles = files === null || files === void 0 ? void 0 : files.filter(function (_, idx) {
        return idx !== index;
      });
      onChange(newFiles);
    };
  }, [files]);
  useEffect(function () {
    uploadError && setError(uploadError);
  }, [uploadError]);
  var onDropAccepted = /*#__PURE__*/function () {
    var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee(acceptedFiles) {
      var initialFiles, updatedFiles, newFiles, _updatedFiles;
      return _regenerator().w(function (_context) {
        while (1) switch (_context.n) {
          case 0:
            setTouched(false);
            setUploadError("");
            initialFiles = acceptedFiles.map(function (file) {
              return {
                name: file.name,
                size: file.size
              };
            });
            updatedFiles = multiple ? [].concat(_toConsumableArray(files || []), _toConsumableArray(initialFiles)) : initialFiles;
            onChange(updatedFiles);
            _context.n = 1;
            return new Promise(function (resolve) {
              var files = [];
              acceptedFiles.forEach(function (file) {
                setUploadProgress(assoc(file.name, 0));
                var upload = new DirectUpload(file, DIRECT_UPLOAD_URL, {
                  directUploadWillStoreFileWithXHR: function directUploadWillStoreFileWithXHR(xhr) {
                    xhr.upload.addEventListener("progress", function (event) {
                      var percentComplete = Math.round(event.loaded / event.total * 100);
                      setUploadProgress(assoc(file.name, percentComplete));
                    });
                    xhr.upload.addEventListener("load", function () {
                      setUploadProgress(assoc(file.name, undefined));
                    });
                  }
                });
                upload.create(function (error, blob) {
                  if (error) {
                    return setUploadError(error);
                  }
                  files.push({
                    url: blob.blob_url,
                    name: blob.filename,
                    signedId: blob.signed_id
                  });
                  var isUploadCompleted = multiple ? acceptedFiles.length === files.length : files.length === 1;
                  if (isUploadCompleted) {
                    return resolve(files);
                  }
                  return "";
                });
              });
              return files;
            });
          case 1:
            newFiles = _context.v;
            if (multiple) {
              _updatedFiles = filesRef.current.map(function (file) {
                var uploadedFile = findBy({
                  name: file.name
                }, newFiles);
                return _objectSpread$1(_objectSpread$1({}, file), uploadedFile);
              });
              onChange(_updatedFiles);
            } else {
              onChange(newFiles);
            }
          case 2:
            return _context.a(2);
        }
      }, _callee);
    }));
    return function onDropAccepted(_x) {
      return _ref2.apply(this, arguments);
    };
  }();
  var onDropRejected = function onDropRejected(fileRejections) {
    fileRejections.forEach(function (fileObject) {
      setTouched(true);
      if (fileObject.errors[0].code === "too-many-files") {
        setUploadError(renderErrorMessage(fileObject, maxFileSize, multiple));
      } else {
        setUploadError(renderErrorMessage(fileObject, maxFileSize, multiple));
      }
    });
  };
  var _useDropzone = useDropzone(_objectSpread$1({
      disabled: disabled,
      accept: accept,
      multiple: multiple,
      minSize: convertMbToBytes(minFileSize),
      onDropAccepted: onDropAccepted,
      onDropRejected: onDropRejected
    }, maxFileSize && hasFileSizeLimit && {
      maxSize: convertMbToBytes(maxFileSize)
    })),
    getRootProps = _useDropzone.getRootProps,
    getInputProps = _useDropzone.getInputProps,
    isDragActive = _useDropzone.isDragActive,
    fileRejections = _useDropzone.fileRejections;
  return {
    progress: uploadProgress,
    cancel: cancel,
    getRootProps: getRootProps,
    getInputProps: getInputProps,
    isDragActive: isDragActive,
    fileRejections: fileRejections
  };
};

var FileUpload = function FileUpload(_ref) {
  var _ref$allowedFileTypes = _ref.allowedFileTypes,
    allowedFileTypes = _ref$allowedFileTypes === void 0 ? "" : _ref$allowedFileTypes,
    _ref$multipleFilesAll = _ref.multipleFilesAllowed,
    multipleFilesAllowed = _ref$multipleFilesAll === void 0 ? true : _ref$multipleFilesAll,
    _ref$maxFileSize = _ref.maxFileSize,
    maxFileSize = _ref$maxFileSize === void 0 ? MAX_FILE_SIZE : _ref$maxFileSize,
    _ref$hasFileSizeLimit = _ref.hasFileSizeLimit,
    hasFileSizeLimit = _ref$hasFileSizeLimit === void 0 ? true : _ref$hasFileSizeLimit,
    _ref$isPreview = _ref.isPreview,
    isPreview = _ref$isPreview === void 0 ? false : _ref$isPreview,
    _ref$minFileSize = _ref.minFileSize,
    minFileSize = _ref$minFileSize === void 0 ? 0 : _ref$minFileSize,
    _ref$files = _ref.files,
    files = _ref$files === void 0 ? [] : _ref$files,
    _ref$onChange = _ref.onChange,
    onChange = _ref$onChange === void 0 ? noop : _ref$onChange,
    error = _ref.error,
    _ref$setError = _ref.setError,
    setError = _ref$setError === void 0 ? noop : _ref$setError,
    _ref$setTouched = _ref.setTouched,
    setTouched = _ref$setTouched === void 0 ? noop : _ref$setTouched;
  var _useFileUpload = useFileUpload({
      disabled: isPreview,
      accept: getAcceptedFileTypes(allowedFileTypes),
      multiple: multipleFilesAllowed,
      maxFileSize: maxFileSize,
      minFileSize: minFileSize,
      files: files,
      onChange: onChange,
      setError: setError,
      setTouched: setTouched,
      hasFileSizeLimit: hasFileSizeLimit
    }),
    progress = _useFileUpload.progress,
    cancel = _useFileUpload.cancel,
    getRootProps = _useFileUpload.getRootProps,
    getInputProps = _useFileUpload.getInputProps,
    isDragActive = _useFileUpload.isDragActive,
    fileRejections = _useFileUpload.fileRejections;
  var maxFileSizeInBytes = maxFileSize * 1000000;
  var isUploadingFile = function isUploadingFile(file) {
    return isNotNil(progress[file.name]) && (progress[file.name] !== 100 || !file.url);
  };
  var shouldShowError = error && isEmpty(fileRejections);
  return /*#__PURE__*/jsxs(Fragment, {
    children: [/*#__PURE__*/jsx(DropZone, {
      allowedFileTypes: allowedFileTypes,
      getInputProps: getInputProps,
      getRootProps: getRootProps,
      hasFileSizeLimit: hasFileSizeLimit,
      isDragActive: isDragActive,
      maxFileSize: maxFileSize,
      multipleFilesAllowed: multipleFilesAllowed
    }), !isEmpty(files) && /*#__PURE__*/jsx("ul", {
      className: "neeto-molecules-file-upload__uploaded-list",
      children: files === null || files === void 0 ? void 0 : files.map(function (file, idx) {
        return /*#__PURE__*/createElement(FilePreview, {
          file: file,
          cancel: cancel(idx),
          isUploading: isUploadingFile(file),
          key: idx,
          progress: progress[file.name]
        });
      })
    }), isNotEmpty(fileRejections) && /*#__PURE__*/jsx(ErrorMessages, {
      fileRejections: fileRejections,
      maxFileSizeInBytes: maxFileSizeInBytes
    }), shouldShowError && /*#__PURE__*/jsx("p", {
      className: "neeto-molecules-input__error-text",
      "data-cy": "form-file-upload-input-error",
      children: /*#__PURE__*/jsx("span", {
        className: "neeto-molecules-input__error-text-style-handle",
        children: error
      })
    })]
  });
};

var _excluded = ["name"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var FormikFileUpload = function FormikFileUpload(_ref) {
  var name = _ref.name,
    props = _objectWithoutProperties(_ref, _excluded);
  var _useField = useField(name),
    _useField2 = _slicedToArray(_useField, 3);
    _useField2[0];
    var _useField2$ = _useField2[1],
    value = _useField2$.value,
    touched = _useField2$.touched,
    error = _useField2$.error,
    _useField2$2 = _useField2[2],
    setValue = _useField2$2.setValue,
    setTouched = _useField2$2.setTouched,
    setError = _useField2$2.setError;
  var errorToDisplay = touched && error ? error : "";
  return /*#__PURE__*/jsx(FileUpload, _objectSpread(_objectSpread({}, _objectSpread(_objectSpread({}, props), {}, {
    setError: setError,
    setTouched: setTouched
  })), {}, {
    error: errorToDisplay,
    files: value,
    onChange: setValue
  }));
};

export { FileUpload, FormikFileUpload };
//# sourceMappingURL=FileUpload.js.map
