"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _typeof = require("@babel/runtime/helpers/typeof");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _react = _interopRequireWildcard(require("react"));

var _uiTypography = _interopRequireDefault(require("@teamleader/ui-typography"));

var _classnames = _interopRequireDefault(require("classnames"));

var _theme = _interopRequireDefault(require("./theme.css"));

var _utils = require("./utils");

var _tag = _interopRequireDefault(require("../tag"));

var _link = _interopRequireDefault(require("../link"));

var _box = _interopRequireDefault(require("../box"));

var _Autocomplete = _interopRequireDefault(require("./Autocomplete"));

var _overlay = _interopRequireDefault(require("../overlay"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

var ENTER = 'Enter';
var ESCAPE = 'Escape';
var BACKSPACE = 'Backspace';
var UP_ARROW = 'ArrowUp';
var DOWN_ARROW = 'ArrowDown';
var SEMI = ';';
var COMMA = ',';

var Label = function Label(_ref) {
  var option = _ref.option,
      _ref$suggestions = _ref.suggestions,
      suggestions = _ref$suggestions === void 0 ? [] : _ref$suggestions,
      editing = _ref.editing,
      invalid = _ref.invalid,
      index = _ref.index,
      onClick = _ref.onClick,
      onFocus = _ref.onFocus,
      onBlur = _ref.onBlur,
      onRemove = _ref.onRemove,
      onFinish = _ref.onFinish,
      renderSuggestion = _ref.renderSuggestion,
      menuWidth = _ref.menuWidth,
      disableRemovalOfFirst = _ref.disableRemovalOfFirst;

  var _useState = (0, _react.useState)(option.email),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      content = _useState2[0],
      setContent = _useState2[1];

  var _useState3 = (0, _react.useState)(true),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      autocompleteOpen = _useState4[0],
      setAutocompleteOpen = _useState4[1];

  var ref = (0, _react.useRef)(null);
  var validSuggestions = (0, _react.useMemo)(function () {
    return (0, _utils.filterSuggestions)(content, suggestions);
  }, [content, suggestions]);

  var _useState5 = (0, _react.useState)(null),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      selectedSuggestion = _useState6[0],
      setSelectedSuggestion = _useState6[1];

  var hasValidSuggestions = autocompleteOpen && (Array.isArray(validSuggestions) ? validSuggestions : Object.keys(validSuggestions)).length > 0;
  (0, _react.useEffect)(function () {
    if (editing) {
      setContent(option.email);
      ref.current && (0, _utils.selectContentEditable)(ref.current);
    }
  }, [editing, option]);
  var onTagClick = (0, _react.useCallback)(function (event) {
    onClick && onClick(index);
    event.stopPropagation();
    event.preventDefault();
  }, [index, onClick]);
  var onTagFocus = (0, _react.useCallback)(function () {
    onFocus && onFocus(index);
  }, [index, onFocus]);
  var onTagRemove = (0, _react.useCallback)(function (event) {
    onRemove && onRemove(index);
    event.stopPropagation();
    event.preventDefault();
  }, [index, onRemove]);
  var onChange = (0, _react.useCallback)(function (event) {
    setContent(event.target.innerText);
  }, [setContent]);
  var onTagBlur = (0, _react.useCallback)(function (event) {
    var trimmedContent = content.trim();
    onBlur && onBlur(index, trimmedContent === option.email ? option : {
      email: trimmedContent
    });
    event.stopPropagation();
    event.preventDefault();
  }, [onBlur, index, option, content]);
  var onInputBlur = (0, _react.useCallback)(function (event) {
    if (event.relatedTarget) {
      onTagBlur(event);
    }
  }, [onTagBlur]);
  var onKeyDown = (0, _react.useCallback)(function (event) {
    var trimmedContent = content.trim();

    switch (event.key) {
      case ENTER:
        {
          var newOption = selectedSuggestion && (0, _utils.validateSuggestion)(trimmedContent, selectedSuggestion) ? selectedSuggestion : trimmedContent === option.email ? option : {
            email: trimmedContent
          };
          onFinish && onFinish(index, newOption);
          event.preventDefault();
          break;
        }

      case COMMA:
      case SEMI:
        onFinish && onFinish(index, trimmedContent === option.email ? option : {
          email: trimmedContent
        });
        event.preventDefault();
        break;

      case ESCAPE:
        if (hasValidSuggestions) {
          setAutocompleteOpen(false);
          event.stopPropagation();
          break;
        }

        onFinish && onFinish(index, option);
        break;

      case BACKSPACE:
        if (!event.repeat && content === '' && onRemove && !((index === 0 || index === 1) && disableRemovalOfFirst)) {
          onRemove(index);
        }

        break;

      case UP_ARROW:
        setSelectedSuggestion((0, _utils.moveSuggestion)(validSuggestions, selectedSuggestion, -1));
        event.preventDefault();
        break;

      case DOWN_ARROW:
        setSelectedSuggestion((0, _utils.moveSuggestion)(validSuggestions, selectedSuggestion, 1));
        event.preventDefault();
        break;

      default:
        if (!autocompleteOpen) {
          setAutocompleteOpen(true);
        }

    }
  }, [onFinish, index, content, option, hasValidSuggestions, onRemove, validSuggestions, selectedSuggestion, autocompleteOpen]);
  var onSuggestionClick = (0, _react.useCallback)(function (suggestion, event) {
    onFinish && onFinish(index, suggestion);
    event.stopPropagation();
    event.preventDefault();
  }, [index, onFinish]);
  var onSuggestionHover = (0, _react.useCallback)(function (suggestion) {
    setSelectedSuggestion(suggestion);
  }, [setSelectedSuggestion]);

  if (editing) {
    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, hasValidSuggestions && /*#__PURE__*/_react.default.createElement(_overlay.default, {
      active: true,
      onOverlayClick: onTagBlur,
      backdrop: "",
      className: _theme.default['label-overlay']
    }), /*#__PURE__*/_react.default.createElement(_box.default, {
      contentEditable: true,
      suppressContentEditableWarning: true,
      tabIndex: 0,
      className: (0, _classnames.default)(_theme.default['label--editing'], _uiTypography.default['text'], _uiTypography.default['text-body']),
      ref: ref,
      onInput: onChange,
      onKeyDown: onKeyDown,
      onBlur: hasValidSuggestions ? onInputBlur : onTagBlur
    }, option.email), hasValidSuggestions && /*#__PURE__*/_react.default.createElement(_Autocomplete.default, {
      suggestions: validSuggestions,
      highlightedSuggestion: selectedSuggestion,
      onClick: onSuggestionClick,
      onHover: onSuggestionHover,
      renderSuggestion: renderSuggestion,
      menuWidth: menuWidth
    }));
  }

  return /*#__PURE__*/_react.default.createElement(_tag.default, {
    className: invalid ? _theme.default['label--error'] : undefined,
    margin: 1,
    marginRight: 2,
    onFocus: onTagFocus,
    onRemoveClick: !(index === 0 && disableRemovalOfFirst) && onRemove ? onTagRemove : undefined
  }, /*#__PURE__*/_react.default.createElement(_link.default, {
    element: "button",
    className: _theme.default['label-text'],
    inherit: false,
    onClick: onTagClick
  }, option.label || option.email));
};

var _default = Label;
exports.default = _default;