import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import React, { useCallback, useState, useEffect, useRef, useMemo } from 'react';
import uiTypography from '@teamleader/ui-typography';
import cx from 'classnames';
import theme from './theme.css';
import { filterSuggestions, moveSuggestion, selectContentEditable, validateSuggestion } from './utils';
import Tag from '../tag';
import Link from '../link';
import Box from '../box';
import Autocomplete from './Autocomplete';
import Overlay from '../overlay';
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 = useState(option.email),
      _useState2 = _slicedToArray(_useState, 2),
      content = _useState2[0],
      setContent = _useState2[1];

  var _useState3 = useState(true),
      _useState4 = _slicedToArray(_useState3, 2),
      autocompleteOpen = _useState4[0],
      setAutocompleteOpen = _useState4[1];

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

  var _useState5 = useState(null),
      _useState6 = _slicedToArray(_useState5, 2),
      selectedSuggestion = _useState6[0],
      setSelectedSuggestion = _useState6[1];

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

    switch (event.key) {
      case ENTER:
        {
          var newOption = selectedSuggestion && 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(moveSuggestion(validSuggestions, selectedSuggestion, -1));
        event.preventDefault();
        break;

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

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

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

  if (editing) {
    return /*#__PURE__*/React.createElement(React.Fragment, null, hasValidSuggestions && /*#__PURE__*/React.createElement(Overlay, {
      active: true,
      onOverlayClick: onTagBlur,
      backdrop: "",
      className: theme['label-overlay']
    }), /*#__PURE__*/React.createElement(Box, {
      contentEditable: true,
      suppressContentEditableWarning: true,
      tabIndex: 0,
      className: cx(theme['label--editing'], uiTypography['text'], uiTypography['text-body']),
      ref: ref,
      onInput: onChange,
      onKeyDown: onKeyDown,
      onBlur: hasValidSuggestions ? onInputBlur : onTagBlur
    }, option.email), hasValidSuggestions && /*#__PURE__*/React.createElement(Autocomplete, {
      suggestions: validSuggestions,
      highlightedSuggestion: selectedSuggestion,
      onClick: onSuggestionClick,
      onHover: onSuggestionHover,
      renderSuggestion: renderSuggestion,
      menuWidth: menuWidth
    }));
  }

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

export default Label;