import React, { useState, useRef } from 'react';
import classnames from 'classnames';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const isFilesAccepted = (acceptedFileTypes, file) => acceptedFileTypes?.some(fileType => file?.name.endsWith(fileType));
/**
 * Counter is used to indicate amount of entities somewhere
 * @uxr-only-supported
 * @midnight-gray-supported
 * @alpine-light-supported
 * */
export function FilesUploadArea({
  testId,
  className,
  children,
  onDrag,
  acceptedFiles,
  inputProps,
  onIncorrectFileType,
  dragText
}) {
  const [dragActive, setDragActive] = useState(false);
  const inputRef = useRef(null);
  const dragContainer = useRef(null);
  const handleDrop = event => {
    event.preventDefault();
    event.stopPropagation();
    setDragActive(false);
    const droppedFiles = Array.from(event.dataTransfer.files);
    const notAccepted = droppedFiles.filter(file => !isFilesAccepted(acceptedFiles, file));
    const accepted = droppedFiles.filter(file => isFilesAccepted(acceptedFiles, file));
    if (notAccepted.length) {
      onIncorrectFileType?.(notAccepted);
    }
    if (accepted.length) {
      onDrag?.(accepted);
    }
  };
  const handleDragOver = event => {
    event.preventDefault();
    event.stopPropagation();
    setDragActive(true);
  };
  const handleDragLeave = event => {
    event.preventDefault();
    event.stopPropagation();
    if (event.target === dragContainer.current) {
      setDragActive(false);
    }
  };
  const upload = () => {
    inputRef.current?.click();
  };
  const onInputChange = event => {
    event.preventDefault();
    event.stopPropagation();
    if (event.target.files) {
      const droppedFiles = Array.from(event.target.files);
      onDrag?.(droppedFiles);
    }
    // Reset the input value to allow re-uploading the same file without rerendering the input
    // HTML input doesn't trigger change event when the same file is selected
    event.target.value = '';
  };
  return /*#__PURE__*/_jsxs("div", {
    onDragOver: handleDragOver,
    onDragLeave: handleDragLeave,
    ref: dragContainer,
    onDrop: handleDrop,
    className: classnames('files-upload-area', className, dragActive && 'drag-active'),
    "test-id": testId,
    children: [/*#__PURE__*/_jsx("input", {
      className: "files-upload-area-input",
      name: "files-upload-area",
      "test-id": "files-upload-area",
      type: "file",
      onChange: onInputChange,
      accept: acceptedFiles?.toString(),
      multiple: true,
      ref: inputRef,
      "aria-hidden": true,
      ...inputProps
    }), typeof children === 'function' ? children({
      upload
    }) : children, dragActive && /*#__PURE__*/_jsx("div", {
      className: "files-upload-area-overlay",
      "test-id": "files-upload-area-overlay",
      children: /*#__PURE__*/_jsx("p", {
        className: "files-upload-area-overlay-text",
        children: dragText
      })
    })]
  });
}