import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
var _excluded = ["file", "showSize", "previewImg", "error", "warning", "multiple", "disabled", "hovered", "focused", "size", "view", "withValidationTooltip", "validationTooltipPosition", "withWarningIcon", "onRemove", "showFilenameHint", "fileTypeIcon"];
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { globalObject } from '@skbkontur/global-object';
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { isThemeGTE } from "../../../lib/theming/ThemeHelpers";
import { forwardRefAndName } from "../../../lib/forwardRefAndName";
import { FileUploaderFileStatus, getFileUploaderTypeIcon } from "../../../internal/FileUploaderControl/fileUtils";
import { formatBytes } from "../../../lib/utils";
import { TextWidthHelper } from "../../../internal/TextWidthHelper/TextWidthHelper";
import { truncate } from "../../../lib/stringUtils";
import { cx } from "../../../lib/theming/Emotion";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { keyListener } from "../../../lib/events/keyListener";
import { isKeyEnter } from "../../../lib/events/keyboard/identifiers";
import { Hint } from "../../Hint";
import { Tooltip } from "../../Tooltip";
import { getDOMRect } from "../../../lib/dom/getDOMRect";
import { useFileUploaderSize } from "../../../internal/FileUploaderControl/hooks/useFileUploaderSize";
import { FileUploaderFileStatusIcon } from "../../../internal/FileUploaderControl/FileUploaderFile/icons/FileUploaderFileStatusIcon";
import { FileUploaderFileTypeIcon } from "../../../internal/FileUploaderControl/FileUploaderFile/icons/FileUploaderFileTypeIcon";
import { jsStyles, jsRowStyles, jsTileStyles } from "../../../internal/FileUploaderControl/FileUploaderFile/FileUploaderFile.styles";
import { LoadingIcon } from "../../../internal/icons2022/LoadingIcon";
var splitFileNameAndExtension = function splitFileNameAndExtension(filename) {
  var lastDotIndex = filename.lastIndexOf('.');
  if (lastDotIndex === -1) {
    return {
      name: filename,
      extension: ''
    };
  }
  var name = filename.substring(0, lastDotIndex);
  var extension = filename.substring(lastDotIndex + 1);
  return {
    name: name,
    extension: extension
  };
};
var getTruncatedName = function getTruncatedName(fileNameWidth, fileNameElementWidth, name, isTileView) {
  if (isTileView === void 0) {
    isTileView = false;
  }
  if (!fileNameWidth && !fileNameElementWidth) {
    return null;
  }
  if (fileNameWidth <= fileNameElementWidth) {
    return name;
  }
  var charWidth = Math.ceil(fileNameWidth / name.length);
  var maxCharsCountInSpan = Math.ceil(fileNameElementWidth / charWidth);
  if (isTileView) {
    var splitFileName = splitFileNameAndExtension(name);
    return truncate(splitFileName.name, maxCharsCountInSpan) + "." + splitFileName.extension;
  }
  return truncate(name, maxCharsCountInSpan);
};
var calcTruncatedName = function calcTruncatedName(textHelperRef, fileNameElementRef, name, isTileView) {
  var _textHelperRef$curren;
  if (isTileView === void 0) {
    isTileView = false;
  }
  var fileNameWidth = ((_textHelperRef$curren = textHelperRef.current) == null ? void 0 : _textHelperRef$curren.getTextWidth()) || 0;
  var fileNameElementWidth = isTileView ?
  // даем возможность занять 2 строки с погрешностью в 50%
  getDOMRect(fileNameElementRef.current).width * 1.5 : getDOMRect(fileNameElementRef.current).width;
  return getTruncatedName(fileNameWidth, fileNameElementWidth, name, isTileView);
};
export var FileUploaderFileDataTids = {
  file: 'FileUploader__file',
  fileTooltip: 'FileUploader__fileTooltip',
  fileName: 'FileUploader__fileName',
  fileSize: 'FileUploader__fileSize',
  fileIcon: 'FileUploader__fileIcon',
  fileTypeIcon: 'FileUploader__fileTypeIcon'
};

/**
 * Компонент файла `FileUploaderFile` из FileUploader для отрисовки загруженного файла.
 */
export var FileUploaderFile = forwardRefAndName('FileUploaderFile', function (props, ref) {
  var _cx, _cx2, _ref, _ref2;
  var file = props.file,
    _props$showSize = props.showSize,
    showSize = _props$showSize === void 0 ? false : _props$showSize,
    previewImg = props.previewImg,
    error = props.error,
    warning = props.warning,
    multiple = props.multiple,
    _props$disabled = props.disabled,
    disabled = _props$disabled === void 0 ? false : _props$disabled,
    _props$hovered = props.hovered,
    hovered = _props$hovered === void 0 ? false : _props$hovered,
    _props$focused = props.focused,
    focused = _props$focused === void 0 ? false : _props$focused,
    size = props.size,
    _props$view = props.view,
    view = _props$view === void 0 ? 'row' : _props$view,
    withValidationTooltip = props.withValidationTooltip,
    validationTooltipPosition = props.validationTooltipPosition,
    withWarningIcon = props.withWarningIcon,
    onRemove = props.onRemove,
    _props$showFilenameHi = props.showFilenameHint,
    showFullFilename = _props$showFilenameHi === void 0 ? true : _props$showFilenameHi,
    fileTypeIcon = props.fileTypeIcon,
    rest = _objectWithoutPropertiesLoose(props, _excluded);
  var id = file.id,
    originalFile = file.originalFile,
    status = file.status,
    validationResult = file.validationResult;
  var name = originalFile.name,
    fileSize = originalFile.size;
  var _useState = useState(hovered || false),
    hoveredFile = _useState[0],
    setHoveredFile = _useState[1];
  var _useState2 = useState(focused || false),
    focusedByTab = _useState2[0],
    setFocusedByTab = _useState2[1];
  var _useState3 = useState(null),
    truncatedFileName = _useState3[0],
    setTruncatedFileName = _useState3[1];
  var textHelperRef = useRef(null);
  var fileNameElementRef = useRef(null);
  var theme = useContext(ThemeContext);
  var versionGTE5_5 = isThemeGTE(theme, '5.5');
  var isLoading = status === FileUploaderFileStatus.Loading;
  var isTileView = versionGTE5_5 && view === 'tile';
  var jsViewStyles = isTileView ? jsTileStyles : jsRowStyles;
  var validationTooltipPositionByView = validationTooltipPosition || (isTileView ? 'top center' : 'top left');
  var formattedSize = useMemo(function () {
    return formatBytes(fileSize, 1);
  }, [fileSize]);
  useEffect(function () {
    var truncatedName = calcTruncatedName(textHelperRef, fileNameElementRef, name, isTileView);
    setTruncatedFileName(truncatedName);
  });
  var handleRemove = useCallback(function (event) {
    event.preventDefault();
    event.stopPropagation();
    onRemove(id);
  }, [id, onRemove]);
  var isValid = validationResult.isValid,
    message = validationResult.message;
  var isError = file.status === FileUploaderFileStatus.Error || error;
  var isWarning = file.status === FileUploaderFileStatus.Warning || warning;
  var isInvalid = isError || !isValid;
  var sizeIconClass = useFileUploaderSize(size, {
    small: jsViewStyles.iconSmall(theme),
    medium: jsViewStyles.iconMedium(theme),
    large: jsViewStyles.iconLarge(theme)
  });
  var renderTooltipContent = useCallback(function () {
    return !isValid && !error && message ? message : null;
  }, [isValid, error, message]);
  var sizeNameBlockClass = useFileUploaderSize(size, {
    small: jsStyles.contentSmall(theme),
    medium: jsStyles.contentMedium(theme),
    large: jsStyles.contentLarge(theme)
  });
  var sizeViewNameBlockClass = useFileUploaderSize(size, {
    small: jsViewStyles.contentSmall(theme),
    medium: jsViewStyles.contentMedium(theme),
    large: jsViewStyles.contentLarge(theme)
  });
  var validationTextClassName = cx((_cx = {}, _cx[jsStyles.validationTextWarning(theme)] = isWarning, _cx[jsStyles.validationTextError(theme)] = isError, _cx));
  var contentClassNames = cx(jsStyles.content(), jsViewStyles.content(), !versionGTE5_5 && (error || !isValid) && jsStyles.error(theme));
  var nameTextClassNames = cx(jsViewStyles.name(), isTileView && !disabled && validationTextClassName);
  var handleMouseEnter = useCallback(function () {
    setHoveredFile(true);
  }, []);
  var handleMouseLeave = useCallback(function () {
    setHoveredFile(false);
  }, []);
  var handleFocus = useCallback(function () {
    // focus event fires before keyDown eventlistener
    // so we should check tabPressed in async way
    globalObject.requestAnimationFrame == null || globalObject.requestAnimationFrame(function () {
      if (keyListener.isTabPressed) {
        setFocusedByTab(true);
      }
    });
  }, []);
  var handleBlur = useCallback(function () {
    setFocusedByTab(false);
  }, []);
  var handleIconKeyDown = useCallback(function (e) {
    if (isKeyEnter(e)) {
      onRemove(id);
    }
  }, [onRemove, id]);
  var iconClassNames = cx(jsStyles.icon(theme), (_cx2 = {}, _cx2[jsStyles.icon5_5(theme)] = versionGTE5_5, _cx2[jsStyles.iconMultiple()] = !versionGTE5_5 && multiple, _cx2[sizeIconClass] = versionGTE5_5, _cx2[jsTileStyles.iconAction(theme)] = isTileView, _cx2[jsTileStyles.iconActionShow()] = isTileView && !disabled && (hovered || hoveredFile || focused || focusedByTab), _cx2));
  var sizeClassName = useFileUploaderSize(size, {
    small: jsStyles.sizeSmall(theme),
    medium: jsStyles.sizeMedium(theme),
    large: jsStyles.sizeLarge(theme)
  });
  var sizeClassNames = cx(jsStyles.size(theme), versionGTE5_5 && (_ref = {}, _ref[sizeClassName] = true, _ref[jsViewStyles.size(theme)] = true, _ref[jsTileStyles.sizeDisabled(theme)] = isTileView && disabled, _ref));
  var sizeFileTypeIconClass = useFileUploaderSize(size, {
    small: jsViewStyles.fileTypeIconSmall(theme),
    medium: jsViewStyles.fileTypeIconMedium(theme),
    large: jsViewStyles.fileTypeIconLarge(theme)
  });
  var isTruncated = truncatedFileName !== name;
  var fileTypeIconClassName = cx(sizeFileTypeIconClass, disabled && jsStyles.disabledFileTypeIconSvg(theme), isTileView && (_ref2 = {}, _ref2[jsTileStyles.fileTypeIcon(theme)] = true, _ref2[jsTileStyles.fileTypeIconPreview()] = !!previewImg, _ref2[jsTileStyles.disabledFileTypeIcon(theme)] = disabled, _ref2[jsTileStyles.warningFileTypeIcon(theme)] = isWarning, _ref2[jsTileStyles.errorFileTypeIcon(theme)] = isError, _ref2), multiple && jsStyles.fileTypeIconMultiple());
  var nameBlockClassNames = cx(sizeNameBlockClass, versionGTE5_5 && sizeViewNameBlockClass, jsStyles.nameBlock(), disabled && jsViewStyles.disabled(theme), jsViewStyles.nameBlock());
  var fileType = getFileUploaderTypeIcon(file.originalFile, isError, isWarning && !!withWarningIcon);
  var icon = isTileView && isLoading ? /*#__PURE__*/
  React.createElement(LoadingIcon, {
    size: size
  }) : fileTypeIcon != null ? fileTypeIcon : /*#__PURE__*/React.createElement(FileUploaderFileTypeIcon, {
    type: fileType,
    size: size,
    view: view
  });
  var splitTruncatedFileName = truncatedFileName && splitFileNameAndExtension(truncatedFileName);
  return /*#__PURE__*/(
    React.createElement(CommonWrapper, rest, /*#__PURE__*/
    React.createElement("div", {
      "data-tid": FileUploaderFileDataTids.file,
      className: jsStyles.root(),
      onMouseEnter: handleMouseEnter,
      onMouseLeave: handleMouseLeave,
      ref: ref
    }, /*#__PURE__*/

    React.createElement(Tooltip, {
      "data-tid": FileUploaderFileDataTids.fileTooltip,
      pos: versionGTE5_5 ? validationTooltipPositionByView : 'right middle',
      render: function render() {
        return withValidationTooltip || isTileView || !versionGTE5_5 ? renderTooltipContent() : null;
      }
    }, /*#__PURE__*/

    React.createElement("div", {
      className: contentClassNames
    }, versionGTE5_5 && /*#__PURE__*/
    React.createElement("div", {
      "data-tid": FileUploaderFileDataTids.fileTypeIcon,
      className: fileTypeIconClassName,
      style: previewImg ? {
        backgroundImage: "url(" + previewImg + ")"
      } : undefined
    }, (!isTileView || !previewImg) && icon), /*#__PURE__*/

    React.createElement("div", {
      className: nameBlockClassNames
    }, /*#__PURE__*/
    React.createElement(TextWidthHelper, {
      ref: textHelperRef,
      text: name
    }), /*#__PURE__*/
    React.createElement(Hint, {
      maxWidth: '100%',
      text: showFullFilename && isTruncated ? name : null
    }, /*#__PURE__*/
    React.createElement("span", {
      "data-tid": FileUploaderFileDataTids.fileName,
      ref: fileNameElementRef,
      className: nameTextClassNames
    }, splitTruncatedFileName && /*#__PURE__*/
    React.createElement(React.Fragment, null, splitTruncatedFileName.name, splitTruncatedFileName.extension && /*#__PURE__*/React.createElement("span", null, ".", splitTruncatedFileName.extension)))), !(withValidationTooltip || isTileView) && versionGTE5_5 && /*#__PURE__*/
    React.createElement("span", {
      className: validationTextClassName
    }, renderTooltipContent())), showSize && formattedSize && /*#__PURE__*/
    React.createElement("span", {
      "data-tid": FileUploaderFileDataTids.fileSize,
      className: sizeClassNames
    }, formattedSize), /*#__PURE__*/

    React.createElement("div", {
      className: iconClassNames,
      "data-tid": FileUploaderFileDataTids.fileIcon,
      tabIndex: 0,
      onClick: handleRemove,
      onFocus: handleFocus,
      onBlur: handleBlur,
      onKeyDown: handleIconKeyDown
    }, /*#__PURE__*/

    React.createElement(FileUploaderFileStatusIcon, {
      isTileView: isTileView,
      status: status,
      disabled: disabled,
      hovered: hovered || hoveredFile,
      focusedByTab: focused || focusedByTab,
      isInvalid: isInvalid,
      hasValidation: isError || isWarning,
      size: size
    }))))))
  );
});