"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 _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

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

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

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

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

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

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

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

var _validationText = _interopRequireDefault(require("../validationText"));

var _Label = _interopRequireDefault(require("./Label"));

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

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

var _excluded = ["error", "defaultSelection", "validator", "onChange", "onBlur", "onFocus", "id", "suggestions", "renderSuggestion", "warning", "menuFullWidth", "disableRemovalOfFirst"];

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; }

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) { (0, _defineProperty2.default)(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; }

var EmailSelector = function EmailSelector(_ref) {
  var _cx;

  var error = _ref.error,
      defaultSelection = _ref.defaultSelection,
      validator = _ref.validator,
      onChange = _ref.onChange,
      onBlur = _ref.onBlur,
      onFocus = _ref.onFocus,
      id = _ref.id,
      suggestions = _ref.suggestions,
      renderSuggestion = _ref.renderSuggestion,
      warning = _ref.warning,
      menuFullWidth = _ref.menuFullWidth,
      disableRemovalOfFirst = _ref.disableRemovalOfFirst,
      rest = (0, _objectWithoutProperties2.default)(_ref, _excluded);
  var ref = (0, _react.useRef)(null);
  var inputRef = (0, _react.useRef)(null);
  var validateLabel = (0, _react.useCallback)(function (option) {
    return _objectSpread(_objectSpread({}, option), {}, {
      valid: validator ? validator(option) === true : undefined
    });
  }, [validator]);

  var _useState = (0, _react.useState)(Array.isArray(defaultSelection) ? defaultSelection.map(validateLabel) : []),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      selection = _useState2[0],
      setSelection = _useState2[1];

  var _useState3 = (0, _react.useState)(null),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      editingLabel = _useState4[0],
      setEditingLabel = _useState4[1];

  var _useState5 = (0, _react.useState)(false),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      internalWarning = _useState6[0],
      setInternalWarning = _useState6[1];

  var validSuggestions = (0, _react.useMemo)(function () {
    if (!suggestions) {
      return [];
    }

    return (0, _utils.excludeSuggestions)(selection, suggestions);
  }, [suggestions, selection]);
  var changeHandler = (0, _react.useCallback)(function (selection) {
    onChange && onChange(selection.filter(function (selection) {
      return selection.email.trim() !== '';
    }));
  }, [onChange]);
  var onLabelClick = (0, _react.useCallback)(function (index) {
    !disableRemovalOfFirst && setEditingLabel(index);
    setSelection(selection.filter(function (selection, i) {
      return i <= index || selection.email.trim() !== '';
    }));
  }, [setEditingLabel, setSelection, selection]);

  var createNewLabel = function createNewLabel(selection) {
    var newSelection = selection.filter(function (selection) {
      return selection.email.trim() !== '';
    });
    newSelection.push({
      email: ''
    });
    setSelection(newSelection);
    setEditingLabel(newSelection.length - 1);
  };

  var onUpdateLabel = (0, _react.useCallback)(function (index, newLabel) {
    var newSelection = (0, _toConsumableArray2.default)(selection);

    if (!newLabel || newLabel.email.trim() === '') {
      newSelection.splice(index, 1);
      setSelection(newSelection);
      setEditingLabel(null);
      onBlur && onBlur();
    } else {
      var result = validator ? validator(newLabel) : true;

      if (result === false) {
        setInternalWarning(true);
        return false;
      }

      if (typeof result === 'string') {
        setInternalWarning(result);
        return false;
      }

      newSelection.splice(index, 1, validateLabel(newLabel));
      createNewLabel(newSelection);
    }

    setInternalWarning(false);
    changeHandler(newSelection);
    return true;
  }, [selection, changeHandler, onBlur, validator, validateLabel]);
  var onBlurLabel = (0, _react.useCallback)(function (index, newLabel) {
    var newSelection = (0, _toConsumableArray2.default)(selection);

    if (!newLabel || newLabel.email.trim() === '') {
      newSelection.splice(index, 1);
    } else {
      newSelection.splice(index, 1, validateLabel(newLabel));
    }

    setInternalWarning(false);
    setSelection(newSelection);
    setEditingLabel(null);
    onBlur && onBlur();
    changeHandler(newSelection);
  }, [selection, onBlur, changeHandler, validateLabel]);
  var onClick = (0, _react.useCallback)(function () {
    if (editingLabel !== null || selection.length > 0 && selection[selection.length - 1].email.trim() === '') {
      return;
    }

    createNewLabel(selection);
  }, [selection, editingLabel]);
  var onInputFocus = (0, _react.useCallback)(function (event) {
    if (editingLabel === null && event.target === inputRef.current) {
      createNewLabel(selection);
    }
  }, [selection, editingLabel]);
  var onInputBlur = (0, _react.useCallback)(function (event) {
    var _ref$current;

    if (event.relatedTarget && (!((_ref$current = ref.current) !== null && _ref$current !== void 0 && _ref$current.contains(event.relatedTarget)) || event.relatedTarget === inputRef.current)) {
      setInternalWarning(false);
      setSelection(selection.filter(function (selection) {
        return selection.email.trim() !== '';
      }));
      setEditingLabel(null);
      onBlur && onBlur(event);
    }
  }, [selection, onBlur]);
  var onTagFocus = (0, _react.useCallback)(function () {
    setSelection(selection.filter(function (selection) {
      return selection.email.trim() !== '';
    }));
    setEditingLabel(null);
  }, [selection, setSelection, setEditingLabel]);
  var onRemoveHandler = (0, _react.useCallback)(function (index) {
    if (editingLabel !== index && selection[index].email !== '') {
      onUpdateLabel(index);
      return;
    }

    if (index > 0) {
      var newSelection = (0, _toConsumableArray2.default)(selection);
      newSelection[index] = {
        email: ''
      };
      newSelection.splice(index - 1, 1);
      setSelection(newSelection);
      setEditingLabel(index - 1);
      changeHandler(newSelection);
    }
  }, [editingLabel, selection, onUpdateLabel, changeHandler]);
  var displayedWarning = warning !== null && warning !== void 0 ? warning : internalWarning;
  return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_box.default, (0, _extends2.default)({
    ref: ref,
    className: (0, _classnames.default)(_theme.default['label-input'], (_cx = {}, (0, _defineProperty2.default)(_cx, _theme.default['label-input--warning'], displayedWarning), (0, _defineProperty2.default)(_cx, _theme.default['label-input--error'], error), (0, _defineProperty2.default)(_cx, _theme.default['label-input--active'], editingLabel !== null), _cx)),
    onClick: onClick,
    onBlur: onInputBlur,
    onFocus: onFocus
  }, rest), selection === null || selection === void 0 ? void 0 : selection.map(function (option, i) {
    var _ref$current2;

    return /*#__PURE__*/_react.default.createElement(_Label.default, (0, _extends2.default)({
      key: i,
      index: i,
      option: option,
      editing: editingLabel === i,
      invalid: option.valid === false,
      onClick: onLabelClick,
      onFinish: onUpdateLabel,
      onFocus: onTagFocus,
      onBlur: onBlurLabel,
      onRemove: onRemoveHandler,
      suggestions: validSuggestions,
      renderSuggestion: renderSuggestion,
      disableRemovalOfFirst: disableRemovalOfFirst
    }, menuFullWidth && {
      menuWidth: (_ref$current2 = ref.current) === null || _ref$current2 === void 0 ? void 0 : _ref$current2.offsetWidth
    }));
  }), (editingLabel === null || selection[editingLabel].email !== '') && /*#__PURE__*/_react.default.createElement(_box.default, {
    className: _theme.default['label-input-focuser'],
    element: "input",
    id: id,
    ref: inputRef,
    onFocus: onInputFocus
  })), /*#__PURE__*/_react.default.createElement(_validationText.default, {
    warning: displayedWarning,
    error: !displayedWarning && error
  }));
};

var _default = EmailSelector;
exports.default = _default;