import _extends from "@babel/runtime/helpers/extends";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
var _excluded = ["className", "error", "onInputFocus", "onFocus", "onInputBlur", "onBlur", "success", "warning", "helpText", "width", "locale", "inputClassName", "autoFocus", "onKeyDown"];
import React, { useState, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Editor } from 'react-draft-wysiwyg';
import cx from 'classnames';
import { IconTextBoldMediumOutline, IconTextItalicMediumOutline, IconListNumeredMediumOutline, IconListMediumOutline, IconLinkMediumOutline } from '@teamleader/ui-icons';
import Box, { pickBoxProps } from '../box';
import ValidationText from '../validationText';
import InlineStylingOptions from './InlineStylingOptions';
import ListStylingOptions from './ListStylingOptions';
import LinkOptions from './LinkOptions';
import { linkDecorator } from './decorators';
import theme from './theme.css';
import translations from './translations';
var toolbar = {
  options: ['inline', 'list', 'link'],
  inline: {
    options: ['bold', 'italic'],
    bold: {
      icon: /*#__PURE__*/React.createElement(IconTextBoldMediumOutline, null)
    },
    italic: {
      icon: /*#__PURE__*/React.createElement(IconTextItalicMediumOutline, null)
    },
    component: InlineStylingOptions
  },
  list: {
    component: ListStylingOptions,
    options: ['unordered', 'ordered'],
    unordered: {
      icon: /*#__PURE__*/React.createElement(IconListMediumOutline, null)
    },
    ordered: {
      icon: /*#__PURE__*/React.createElement(IconListNumeredMediumOutline, null)
    }
  },
  link: {
    component: LinkOptions,
    defaultTargetOption: '_self',
    showOpenOptionOnHover: true,
    options: ['link'],
    link: {
      icon: /*#__PURE__*/React.createElement(IconLinkMediumOutline, null)
    }
  }
};
var customStyleMap = {
  BOLD: {
    fontFamily: 'Inter',
    fontWeight: 700
  }
};
var availableLocales = ['en', 'es', 'it', 'nl', 'fr', 'de'];
/** @type {React.ComponentType<any>} */

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

  var className = _ref.className,
      error = _ref.error,
      onInputFocus = _ref.onInputFocus,
      onFocus = _ref.onFocus,
      onInputBlur = _ref.onInputBlur,
      onBlur = _ref.onBlur,
      success = _ref.success,
      warning = _ref.warning,
      helpText = _ref.helpText,
      width = _ref.width,
      _ref$locale = _ref.locale,
      locale = _ref$locale === void 0 ? 'en' : _ref$locale,
      inputClassName = _ref.inputClassName,
      autoFocus = _ref.autoFocus,
      onKeyDown = _ref.onKeyDown,
      others = _objectWithoutProperties(_ref, _excluded);

  var _useState = useState(false),
      _useState2 = _slicedToArray(_useState, 2),
      isFocused = _useState2[0],
      setIsFocused = _useState2[1];

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

  var editorRef = useRef();
  useEffect(function () {
    if (autoFocus) {
      var _editorRef$current;

      // eslint-disable-next-line no-unused-expressions
      editorRef === null || editorRef === void 0 ? void 0 : (_editorRef$current = editorRef.current) === null || _editorRef$current === void 0 ? void 0 : _editorRef$current.focusEditor();
    }
  }, [autoFocus]);
  useEffect(function () {
    var _editorRef$current2;

    if (!onKeyDown || !(editorRef !== null && editorRef !== void 0 && (_editorRef$current2 = editorRef.current) !== null && _editorRef$current2 !== void 0 && _editorRef$current2.wrapper)) {
      return;
    }

    var handleKeyDown = function handleKeyDown(event) {
      return onKeyDown(event);
    };

    editorRef.current.wrapper.addEventListener('keydown', handleKeyDown);
    return function () {
      var _editorRef$current3;

      if (!onKeyDown && !(editorRef !== null && editorRef !== void 0 && (_editorRef$current3 = editorRef.current) !== null && _editorRef$current3 !== void 0 && _editorRef$current3.wrapper)) {
        return;
      }

      editorRef.current.wrapper.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  var handleBlur = function handleBlur(event) {
    var _event$relatedTarget, _event$relatedTarget$;

    var editorInput = document.querySelector("[aria-label='rdw-editor']"); // Only blur when editorInput is blurred and the newly focussed target is not part of the wysiwyg

    if (event.target === editorInput && !((_event$relatedTarget = event.relatedTarget) !== null && _event$relatedTarget !== void 0 && (_event$relatedTarget$ = _event$relatedTarget.dataset) !== null && _event$relatedTarget$ !== void 0 && _event$relatedTarget$.wysiwyg)) {
      setIsFocused(false);
      onBlur && onBlur(event);
    }

    if (onInputBlur) {
      onInputBlur(event);
    }
  };

  var handleFocus = function handleFocus(event) {
    var editorInput = document.querySelector("[aria-label='rdw-editor']"); // Only focus when focussed target is part of the wysiwyg and the editor isn't focussed yet

    if ((event.target.dataset.wysiwyg || event.target === editorInput) && !isFocused) {
      setIsFocused(true);
      onFocus && onFocus(event);
    }

    if (onInputFocus) {
      onInputFocus(event);
    }
  };

  var handleContentStateChange = function handleContentStateChange(_ref2) {
    var _ref2$blocks = _slicedToArray(_ref2.blocks, 1),
        type = _ref2$blocks[0].type;

    if (type === 'unstyled') {
      setIsPlaceholderShown(true);
      return;
    }

    setIsPlaceholderShown(false);
  };

  var wrapperClassNames = cx(theme['wrapper'], (_cx = {}, _defineProperty(_cx, theme['has-focus'], isFocused), _defineProperty(_cx, theme['has-error'], error), _defineProperty(_cx, theme['has-success'], success), _defineProperty(_cx, theme['has-warning'], warning), _defineProperty(_cx, theme['has-placeholder'], isPlaceholderShown), _cx), className);
  var inputClassNames = cx(theme['input'], inputClassName);
  var boxProps = pickBoxProps(others);
  return /*#__PURE__*/React.createElement(Box, _extends({
    style: {
      width: width,
      flex: width && '0 0 auto'
    }
  }, boxProps), /*#__PURE__*/React.createElement(Editor, _extends({
    toolbar: toolbar,
    wrapperClassName: wrapperClassNames,
    editorClassName: inputClassNames,
    toolbarClassName: theme['toolbar'],
    onFocus: handleFocus,
    onBlur: handleBlur,
    onContentStateChange: handleContentStateChange,
    customStyleMap: customStyleMap,
    customDecorators: [linkDecorator],
    localization: availableLocales.includes(locale) ? {
      locale: locale,
      translations: translations[locale]
    } : {
      locale: 'en',
      translations: translations['en']
    },
    ref: editorRef
  }, others)), /*#__PURE__*/React.createElement(ValidationText, {
    error: error,
    help: helpText,
    success: success,
    warning: warning
  }));
};

export default WysiwygEditor;