import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
var _excluded = ["children", "className", "tooltip", "tooltipColor", "tooltipIcon", "tooltipSize", "tooltipShowDelay", "zIndex", "onClick", "onMouseEnter", "onMouseLeave", "tooltipActive"];

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import Transition from 'react-transition-group/Transition';
import cx from 'classnames';
import omit from 'lodash.omit';
import { createPortal } from 'react-dom';
import { getViewport } from '../utils/utils';
import DocumentObjectProvider, { Context as DocumentObjectContext } from '../hoc/DocumentObjectProvider';
import theme from './theme.css';
import uiUtilities from '@teamleader/ui-utilities';
var POSITIONS = {
  BOTTOM: 'bottom',
  HORIZONTAL: 'horizontal',
  LEFT: 'left',
  RIGHT: 'right',
  TOP: 'top',
  VERTICAL: 'vertical'
};
var SIZES = {
  large: {
    padding: 4
  },
  medium: {
    padding: 3
  },
  small: {
    paddingHorizontal: 3,
    paddingVertical: 2
  }
};
/** @type {(component: React.ComponentType<any>) => React.ComponentType<any>} */

var Tooltip = function Tooltip(ComposedComponent) {
  var TooltippedComponent = /*#__PURE__*/function (_Component) {
    _inherits(TooltippedComponent, _Component);

    var _super = _createSuper(TooltippedComponent);

    function TooltippedComponent() {
      var _this;

      _classCallCheck(this, TooltippedComponent);

      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }

      _this = _super.call.apply(_super, [this].concat(args));

      _defineProperty(_assertThisInitialized(_this), "tooltipRoot", _this.props.documentObject.createElement('div'));

      _defineProperty(_assertThisInitialized(_this), "ref", /*#__PURE__*/React.createRef());

      _defineProperty(_assertThisInitialized(_this), "state", {
        active: false,
        position: _this.props.tooltipPosition
      });

      _defineProperty(_assertThisInitialized(_this), "handleMouseEnter", function (event) {
        _this.activate(_this.calculatePosition(event.currentTarget));

        if (_this.props.onMouseEnter) {
          _this.props.onMouseEnter(event);
        }
      });

      _defineProperty(_assertThisInitialized(_this), "handleMouseLeave", function (event) {
        _this.deactivate();

        if (_this.props.onMouseLeave) {
          _this.props.onMouseLeave(event);
        }
      });

      _defineProperty(_assertThisInitialized(_this), "handleClick", function (event) {
        if (_this.props.tooltipHideOnClick && _this.state.active) {
          _this.deactivate();
        }

        if (_this.props.tooltipShowOnClick && !_this.state.active) {
          _this.activate(_this.calculatePosition(event.currentTarget));
        }

        if (_this.props.onClick) {
          _this.props.onClick(event);
        }
      });

      _defineProperty(_assertThisInitialized(_this), "handleTransitionExited", function () {
        _this.props.documentObject.body.removeChild(_this.tooltipRoot);
      });

      _defineProperty(_assertThisInitialized(_this), "handleTransitionEntered", function () {
        var onTooltipEntered = _this.props.onTooltipEntered;
        onTooltipEntered && onTooltipEntered();
      });

      return _this;
    }

    _createClass(TooltippedComponent, [{
      key: "componentDidMount",
      value: function componentDidMount() {
        var tooltipActive = this.props.tooltipActive;

        if (tooltipActive) {
          this.activate(this.calculatePosition(this.ref.current));
        }
      }
    }, {
      key: "componentDidUpdate",
      value: function componentDidUpdate(_ref) {
        var prevTooltipActive = _ref.tooltipActive;
        var tooltipActive = this.props.tooltipActive;
        var active = this.state.active;

        if (tooltipActive !== prevTooltipActive) {
          if (tooltipActive && !active) {
            this.activate(this.calculatePosition(this.ref.current));
          }

          if (!tooltipActive && active) {
            this.deactivate();
          }
        }
      }
    }, {
      key: "getPosition",
      value: function getPosition(element) {
        var tooltipPosition = this.props.tooltipPosition;

        if (tooltipPosition === POSITIONS.HORIZONTAL) {
          var origin = element.getBoundingClientRect();

          var _getViewport = getViewport(),
              windowWidth = _getViewport.width;

          var toRight = origin.left < windowWidth / 2 - origin.width / 2;
          return toRight ? POSITIONS.RIGHT : POSITIONS.LEFT;
        } else if (tooltipPosition === POSITIONS.VERTICAL) {
          var _origin = element.getBoundingClientRect();

          var _getViewport2 = getViewport(),
              windowHeight = _getViewport2.height;

          var toBottom = _origin.top < windowHeight / 2 - _origin.height / 2;
          return toBottom ? POSITIONS.BOTTOM : POSITIONS.TOP;
        }

        return tooltipPosition;
      }
    }, {
      key: "activate",
      value: function activate(_ref2) {
        var top = _ref2.top,
            left = _ref2.left,
            position = _ref2.position;
        this.props.documentObject.body.appendChild(this.tooltipRoot);
        this.setState({
          active: true,
          top: top,
          left: left,
          position: position
        });
      }
    }, {
      key: "deactivate",
      value: function deactivate() {
        this.setState({
          active: false
        });
      }
    }, {
      key: "calculatePosition",
      value: function calculatePosition(element) {
        var tooltipPosition = this.props.tooltipPosition;

        if (typeof element.getBoundingClientRect !== 'function') {
          return {
            top: 0,
            left: 0,
            position: tooltipPosition
          };
        }

        var _element$getBoundingC = element.getBoundingClientRect(),
            top = _element$getBoundingC.top,
            left = _element$getBoundingC.left,
            height = _element$getBoundingC.height,
            width = _element$getBoundingC.width;

        var position = this.getPosition(element);
        var xOffset = window.scrollX || window.pageXOffset;
        var yOffset = window.scrollY || window.pageYOffset;

        if (position === POSITIONS.BOTTOM) {
          return {
            top: top + height + yOffset,
            left: left + width / 2 + xOffset,
            position: position
          };
        } else if (position === POSITIONS.TOP) {
          return {
            top: top + yOffset,
            left: left + width / 2 + xOffset,
            position: position
          };
        } else if (position === POSITIONS.LEFT) {
          return {
            top: top + height / 2 + yOffset,
            left: left + xOffset,
            position: position
          };
        } else if (position === POSITIONS.RIGHT) {
          return {
            top: top + height / 2 + yOffset,
            left: left + width + xOffset,
            position: position
          };
        }
      }
    }, {
      key: "render",
      value: function render() {
        var _this$state = this.state,
            active = _this$state.active,
            left = _this$state.left,
            top = _this$state.top,
            position = _this$state.position;

        var _this$props = this.props,
            children = _this$props.children,
            className = _this$props.className,
            tooltip = _this$props.tooltip,
            tooltipColor = _this$props.tooltipColor,
            tooltipIcon = _this$props.tooltipIcon,
            tooltipSize = _this$props.tooltipSize,
            tooltipShowDelay = _this$props.tooltipShowDelay,
            zIndex = _this$props.zIndex,
            onClick = _this$props.onClick,
            onMouseEnter = _this$props.onMouseEnter,
            onMouseLeave = _this$props.onMouseLeave,
            tooltipActive = _this$props.tooltipActive,
            other = _objectWithoutProperties(_this$props, _excluded);

        var rest = omit(other, ['onTooltipEntered', 'tooltipHideOnClick', 'tooltipPosition', 'tooltipShowOnClick', 'tooltipShowDelay', 'documentObject']);

        var childProps = _objectSpread(_objectSpread({}, rest), {}, {
          className: className,
          onClick: onClick,
          onMouseEnter: onMouseEnter,
          onMouseLeave: onMouseLeave,
          ref: this.ref
        });

        if (tooltipActive === null) {
          childProps = _objectSpread(_objectSpread({}, childProps), {}, {
            onClick: this.handleClick,
            onMouseEnter: this.handleMouseEnter,
            onMouseLeave: this.handleMouseLeave
          });
        }

        return /*#__PURE__*/React.createElement(ComposedComponent, childProps, children, /*#__PURE__*/createPortal( /*#__PURE__*/React.createElement(Transition, {
          in: active,
          onExited: this.handleTransitionExited,
          onEntered: this.handleTransitionEntered,
          timeout: {
            enter: tooltipShowDelay,
            exit: 1000
          }
        }, function (state) {
          var _cx;

          var classNames = cx(uiUtilities['box-shadow-200'], theme['tooltip'], theme[tooltipColor], theme[tooltipSize], (_cx = {}, _defineProperty(_cx, theme['is-entering'], state === 'entering'), _defineProperty(_cx, theme['is-entered'], state === 'entered'), _defineProperty(_cx, theme['is-exiting'], state === 'exiting'), _defineProperty(_cx, theme[position], theme[position]), _cx));
          return /*#__PURE__*/React.createElement("div", {
            className: classNames,
            "data-teamleader-ui": "tooltip",
            style: {
              top: top,
              left: left,
              zIndex: zIndex
            }
          }, /*#__PURE__*/React.createElement(Box, _extends({
            className: theme['inner']
          }, SIZES[tooltipSize]), tooltipIcon && /*#__PURE__*/React.createElement("div", {
            className: theme['icon']
          }, tooltipIcon), /*#__PURE__*/React.createElement("div", {
            className: theme['text']
          }, tooltip)));
        }), this.tooltipRoot));
      }
    }]);

    return TooltippedComponent;
  }(Component);

  TooltippedComponent.defaultProps = {
    className: '',
    tooltipColor: 'white',
    tooltipHideOnClick: true,
    tooltipIcon: null,
    tooltipPosition: POSITIONS.TOP,
    tooltipShowOnClick: false,
    tooltipSize: 'medium',
    tooltipShowDelay: 100,
    zIndex: 700,
    tooltipActive: null
  };
  return DocumentObjectProvider(function (props) {
    return /*#__PURE__*/React.createElement(DocumentObjectContext.Consumer, null, function (documentObject) {
      return /*#__PURE__*/React.createElement(TooltippedComponent, _extends({}, props, {
        documentObject: documentObject
      }));
    });
  });
};

export default Tooltip;