import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";

/* eslint-disable no-unused-expressions */

/* eslint-disable no-restricted-properties */
import React, { useRef, useState } from "react";
import PropTypes from "prop-types";
import cx from "classnames";
import Loader from "../Loading";
import getClasses from "./styles";
import Preview from "./Preview";
import useIsDragover from "./useIsDragover";
import useIsMounted from "./useIsMounted";
import { getBase64Image, bytesToMb } from "../../utils/files";
import mergeRefs from "./mergeRefs";
export var TYPES_ERRORS = {
  limitSize: "Limit size",
  invalidFormat: "Invalid format",
  parse: "Parse image"
};
var ImageField = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var value = _ref.value,
      onChange = _ref.onChange,
      className = _ref.className,
      mbLimit = _ref.mbLimit,
      onError = _ref.onError,
      size = _ref.size,
      label = _ref.label,
      accept = _ref.accept;

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      loading = _useState2[0],
      setLoading = _useState2[1];

  var wrapperRef = useRef(null);
  var inputRef = useRef(null);
  var classes = getClasses({
    size: size
  });
  var isDragover = useIsDragover(wrapperRef);
  var isMounted = useIsMounted();

  var isValidSize = function isValidSize(bytes) {
    return bytesToMb(bytes) <= mbLimit;
  };

  var isValidFormat = function isValidFormat(format) {
    return format && format.startsWith("image/");
  };

  var clearInputFile = function clearInputFile() {
    if (inputRef.current) {
      inputRef.current.value = "";
    }
  };

  var handleChange = function handleChange(ev) {
    var file = ev.target.files[0];
    if (!file) return;

    if (!isValidFormat(file.type)) {
      onError(TYPES_ERRORS.invalidFormat);
      return;
    }

    if (!isValidSize(file.size)) {
      onError(TYPES_ERRORS.limitSize);
      return;
    }

    setLoading(true);
    getBase64Image(file).then(onChange)["catch"](function () {
      return onError(TYPES_ERRORS.parse);
    })["finally"](function () {
      if (isMounted()) {
        clearInputFile();
        setLoading(false);
      }
    });
  };

  var classNameInputArea = cx(classes.inputArea, className, _defineProperty({}, classes.dragging, isDragover));
  var availableFormats = Array.isArray(accept) ? accept.map(function (format) {
    return "image/".concat(format);
  }).join(", ") : "image/".concat(accept);
  return /*#__PURE__*/React.createElement("div", {
    ref: wrapperRef,
    className: classNameInputArea,
    "aria-busy": loading
  }, /*#__PURE__*/React.createElement(Preview, {
    src: value,
    size: size
  }), /*#__PURE__*/React.createElement("input", {
    "aria-label": label,
    disabled: loading,
    ref: mergeRefs(inputRef, ref),
    type: "file",
    onChange: handleChange,
    className: classes.file,
    accept: availableFormats
  }), /*#__PURE__*/React.createElement("div", {
    className: classes.dragNotice
  }), loading && /*#__PURE__*/React.createElement("div", {
    className: classes.loading
  }, /*#__PURE__*/React.createElement(Loader, null)));
});
ImageField.propTypes = {
  onChange: PropTypes.func,
  value: PropTypes.string,
  size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  mbLimit: PropTypes.number,
  onError: PropTypes.func,
  accept: PropTypes.oneOfType([PropTypes.oneOf(["*", "jpg", "jpeg", "png"]), PropTypes.arrayOf(["*", "jpg", "jpeg", "png"])]),
  label: PropTypes.string
};
ImageField.defaultProps = {
  onChange: function onChange() {},
  value: "",
  size: 120,
  mbLimit: 10,
  accept: "*",
  onError: function onError() {},
  label: "Upload image"
};
export default ImageField;