import React, { useRef } from 'react';
import classnames from 'classnames';
import { supportsFolderUpload } from './upload-helper';
import DropdownItemTitle from './dropdown-item-title';
import { useTreeNodeNavigation } from '../hooks/use-tree-navigation/use-tree-node-navigation';
import { getKeyActionFnMenu } from '../hooks/use-tree-navigation/utils';
import DropdownItemTooltip from './dropdown-item-tooltip';
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const isFolderUploadSupported = supportsFolderUpload();
const DropdownItemFileUpload = ({
  option,
  onSelect = () => {},
  onCloseDropdown = () => {}
}) => {
  const {
    disabled,
    id,
    testId,
    acceptedFiles = [],
    isMultiple = false,
    isFolderUpload = false
  } = option;
  const accept = acceptedFiles ? acceptedFiles.join(', ') : '*';
  const labelRef = useRef(null);
  const handleFileSelection = e => {
    if (typeof e === 'boolean') {
      labelRef.current?.click();
    } else {
      e?.preventDefault?.();
      if (e?.target?.files) {
        onSelect(option, {
          selectedFiles: e.target.files
        });
      }
    }
  };
  const {
    treeItemAttrs,
    ref: setRefCallback
  } = useTreeNodeNavigation({
    id: option.privateKey || option.key,
    getKeyActionFn: getKeyActionFnMenu,
    onCustomButtonKeyDown: onCloseDropdown,
    onToggleSelected: handleFileSelection,
    ignoreKeys: null
  });
  if (isFolderUpload && !isFolderUploadSupported) {
    return null;
  }
  return /*#__PURE__*/_jsx(DropdownItemTooltip, {
    option: option,
    children: /*#__PURE__*/_jsxs("label", {
      "test-id": testId,
      htmlFor: id,
      className: classnames('drop-file-upload-label truncated-drop-item', {
        disabled
      }),
      ref: labelRef,
      children: [/*#__PURE__*/_jsx(DropdownItemTitle, {
        option: option
      }), /*#__PURE__*/_jsx("input", {
        className: "drop-file-upload-input",
        "test-id": `drop-file-upload-input-${id}`,
        ref: setRefCallback,
        type: "file",
        id: id,
        disabled: disabled,
        onChange: handleFileSelection,
        accept: accept,
        multiple: isMultiple
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        // @ts-ignore
        ,
        webkitdirectory: isFolderUpload && isFolderUpload.toString() || null,
        onKeyDown: treeItemAttrs.onKeyDown
      })]
    })
  });
};
export default DropdownItemFileUpload;