import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _excluded = ["disabled", "icon", "rightIcon", "use", "loading", "_button", "_buttonOpened", "component", "focused", "error", "warning", "tabIndex", "theme"];
var _class, _Link;
import React from 'react';
import { globalObject } from '@skbkontur/global-object';
import { resetButton } from "../../../lib/styles/Mixins";
import { keyListener } from "../../../lib/events/keyListener";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { isExternalLink } from "../../../lib/utils";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { cx } from "../../../lib/theming/Emotion";
import { rootNode } from "../../../lib/rootNode";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { ThemeFactory } from "../../../lib/theming/ThemeFactory";
import { getVisualStateDataAttributes } from "../../../internal/CommonWrapper/utils/getVisualStateDataAttributes";
import { styles } from "../Link.styles";
import { LinkIcon } from "../LinkIcon";
var LINK_DEFAULT_COMPONENT = 'a';
export var LinkDataTids = {
  root: 'Link__root'
};

/**
 * С помощью ссылки пользователь может перейти на другую страницу, раздел приложения или внешний URL.
 */
export var Link = rootNode(_class = (_Link = /*#__PURE__*/function (_React$Component) {
  function Link() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this;
    _this.getProps = createPropsGetter(Link.defaultProps);
    _this.state = {
      focusedByTab: false
    };
    _this.getTabIndex = function (_ref) {
      var nonInteractive = _ref.nonInteractive,
        _ref$tabIndex = _ref.tabIndex,
        tabIndex = _ref$tabIndex === void 0 ? 0 : _ref$tabIndex;
      return nonInteractive ? -1 : tabIndex;
    };
    _this.getRel = function () {
      if (isAnchorProps(_this.props)) {
        var _this$props = _this.props,
          rel = _this$props.rel,
          href = _this$props.href;
        if (!rel && href) {
          return "noopener" + (isExternalLink(href) ? ' noreferrer' : '');
        }
        return rel;
      }
      return undefined;
    };
    _this.renderMain = function (props) {
      var _cx;
      var disabled = props.disabled,
        icon = props.icon,
        rightIcon = props.rightIcon,
        use = props.use,
        loading = props.loading,
        _button = props._button,
        _buttonOpened = props._buttonOpened,
        Root = props.component,
        _props$focused = props.focused,
        focused = _props$focused === void 0 ? false : _props$focused,
        error = props.error,
        warning = props.warning,
        tabIndex = props.tabIndex,
        theme = props.theme,
        rest = _objectWithoutPropertiesLoose(props, _excluded);
      var arrow = null;
      if (_button) {
        arrow = /*#__PURE__*/React.createElement("span", {
          className: styles.arrow()
        });
      }
      var isFocused = !disabled && (_this.state.focusedByTab || focused);
      var leftIconElement = icon && /*#__PURE__*/React.createElement(LinkIcon, {
        icon: icon,
        loading: loading,
        position: "left"
      });
      var rightIconElement = rightIcon && /*#__PURE__*/
      React.createElement(LinkIcon, {
        hasBothIcons: !!icon && !!rightIcon,
        icon: rightIcon,
        loading: loading,
        position: "right"
      });
      var nonInteractive = disabled || loading;
      var getUseStyles = function getUseStyles() {
        switch (use) {
          case 'default':
            return styles["default"](_this.theme);
          case 'danger':
            return styles.danger(_this.theme);
          case 'success':
            return styles.success(_this.theme);
          case 'grayed':
            return styles.grayed(_this.theme);
        }
      };
      var getUseLineFocusStyles = function getUseLineFocusStyles() {
        switch (use) {
          case 'default':
            return styles.lineFocus(_this.theme);
          case 'danger':
            return styles.lineFocusDanger(_this.theme);
          case 'success':
            return styles.lineFocusSuccess(_this.theme);
          case 'grayed':
            return styles.lineFocusGrayed(_this.theme);
        }
      };
      var rootProps = _extends({}, rest, {
        className: cx((_cx = {}, _cx[styles.root(_this.theme)] = true, _cx[resetButton()] = Root === 'button', _cx[styles.focus(_this.theme)] = isFocused, _cx[styles.disabled(_this.theme)] = disabled || loading, _cx[getUseStyles()] = true, _cx[styles.useGrayedFocus(_this.theme)] = use === 'grayed' && focused, _cx[styles.button(_this.theme)] = !!_button, _cx[styles.buttonOpened(_this.theme)] = !!_buttonOpened, _cx[styles.warning(_this.theme)] = warning, _cx[styles.error(_this.theme)] = error, _cx[getUseLineFocusStyles()] = isFocused, _cx)),
        onClick: _this.handleClick,
        onFocus: _this.handleFocus,
        onBlur: _this.handleBlur,
        tabIndex: _this.getTabIndex({
          nonInteractive: nonInteractive,
          tabIndex: tabIndex
        }),
        rel: _this.getRel()
      });
      var buttonOnlyProps = Root === 'button' ? {
        disabled: nonInteractive
      } : {};
      return /*#__PURE__*/(
        React.createElement(Root, _extends({
          "data-tid": LinkDataTids.root
        }, rootProps, buttonOnlyProps, getVisualStateDataAttributes({
          disabled: disabled
        })), leftIconElement, _this.props.children, rightIconElement, arrow)
      );
    };
    _this.handleFocus = function () {
      if (!_this.props.disabled) {
        // focus event fires before keyDown eventlistener
        // so we should check tabPressed in async way
        globalObject.requestAnimationFrame == null || globalObject.requestAnimationFrame(function () {
          if (keyListener.isTabPressed) {
            _this.setState({
              focusedByTab: true
            });
          }
        });
      }
    };
    _this.handleBlur = function () {
      _this.setState({
        focusedByTab: false
      });
    };
    _this.handleClick = function (event) {
      var _this$props2 = _this.props,
        onClick = _this$props2.onClick,
        disabled = _this$props2.disabled,
        loading = _this$props2.loading;
      if (disabled) {
        event.preventDefault();
        event.stopPropagation();
      }
      if (onClick && !disabled && !loading) {
        onClick(event);
      }
    };
    return _this;
  }
  _inheritsLoose(Link, _React$Component);
  var _proto = Link.prototype;
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = _this2.props.theme ? ThemeFactory.create(_this2.props.theme, theme) : theme;
      return /*#__PURE__*/React.createElement(CommonWrapper, _extends({
        rootNodeRef: _this2.setRootNode
      }, _this2.getProps()), _this2.renderMain);
    });
  };
  return Link;
}(React.Component), _Link.__KONTUR_REACT_UI__ = 'Link', _Link.displayName = 'Link', _Link.defaultProps = {
  use: 'default',
  component: LINK_DEFAULT_COMPONENT
}, _Link)) || _class;
var isAnchorProps = function isAnchorProps(props) {
  return props.component === 'a';
};