import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useEffect, useRef, useState } from 'react';
import Loadable from 'react-loadable';
import { getContextualToolbarItemsFromModule } from '../extensions';
import { nodeToJSON } from '../utils';
import { DropdownMenuItem } from './DropdownMenuItem';
import { DropdownSeparator } from './DropdownSeparator';
var noop = function noop() {
  return null;
};
var isDefaultExport = function isDefaultExport(mod) {
  return mod.hasOwnProperty('default');
};
var resolveExtensionIcon = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(getIcon) {
    var maybeIcon;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          if (getIcon) {
            _context.next = 2;
            break;
          }
          return _context.abrupt("return", noop);
        case 2:
          _context.next = 4;
          return getIcon();
        case 4:
          maybeIcon = _context.sent;
          return _context.abrupt("return", isDefaultExport(maybeIcon) ? maybeIcon.default : maybeIcon);
        case 6:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function resolveExtensionIcon(_x) {
    return _ref.apply(this, arguments);
  };
}();
var convertExtensionToDropdownMenuItem = function convertExtensionToDropdownMenuItem(_ref2) {
  var item = _ref2.item,
    disabled = _ref2.disabled,
    node = _ref2.node,
    extension = _ref2.extension,
    IconComponent = _ref2.IconComponent;
  var title = '';
  if (item.label) {
    title = item.label;
  } else if (typeof item.tooltip === 'string') {
    title = item.tooltip;
  } else if (item.ariaLabel) {
    title = item.ariaLabel;
  }
  item.disabled = (disabled === null || disabled === void 0 ? void 0 : disabled(item.key)) || false;
  var getIcon = function getIcon() {
    var label = item.label || '';
    return IconComponent ? /*#__PURE__*/React.createElement(IconComponent, {
      label: label
    }) : undefined;
  };
  return {
    title: title,
    icon: getIcon(),
    disabled: item.disabled,
    onClick: function onClick() {
      if (typeof item.action !== 'function') {
        throw new Error("'action' of context toolbar item '".concat(item.key, "' is not a function"));
      }
      var targetNodeAdf = nodeToJSON(node);
      extension.extensionApi && item.action(targetNodeAdf, extension.extensionApi);
      return true;
    }
  };
};
var DropdownMenuExtensionItem = function DropdownMenuExtensionItem(_ref3) {
  var item = _ref3.item,
    editorView = _ref3.editorView,
    disabled = _ref3.disabled,
    node = _ref3.node,
    extension = _ref3.extension,
    dropdownOptions = _ref3.dropdownOptions;
  // Use ref to keep icon component stable across renders
  var iconRef = useRef(null);
  if (!iconRef.current && item.icon) {
    iconRef.current = Loadable({
      loader: function loader() {
        return resolveExtensionIcon(item.icon);
      },
      loading: noop
    });
  }
  var dropdownItem = convertExtensionToDropdownMenuItem({
    item: item,
    disabled: disabled,
    node: node,
    extension: extension,
    IconComponent: iconRef.current
  });
  if (!dropdownItem) {
    return null;
  }
  return /*#__PURE__*/React.createElement(DropdownMenuItem, {
    key: item.key,
    item: dropdownItem,
    editorView: editorView,
    hide: dropdownOptions.hide,
    dispatchCommand: dropdownOptions.dispatchCommand,
    showSelected: dropdownOptions.showSelected,
    intl: dropdownOptions.intl
  });
};
export var DropdownMenuExtensionItems = function DropdownMenuExtensionItems(props) {
  var node = props.node,
    editorView = props.editorView,
    extension = props.extension,
    disabled = props.disabled,
    dropdownOptions = props.dropdownOptions,
    areAnyNewToolbarFlagsEnabled = props.areAnyNewToolbarFlagsEnabled;

  // Ignored via go/ees005
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  var _useState = useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    extensions = _useState2[0],
    setExtensions = _useState2[1];
  useEffect(function () {
    getExtensions();
    function getExtensions() {
      return _getExtensions.apply(this, arguments);
    }
    function _getExtensions() {
      _getExtensions = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2() {
        var provider;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              _context2.next = 2;
              return extension.extensionProvider;
            case 2:
              provider = _context2.sent;
              if (!provider) {
                _context2.next = 9;
                break;
              }
              _context2.t0 = setExtensions;
              _context2.next = 7;
              return provider.getExtensions();
            case 7:
              _context2.t1 = _context2.sent;
              (0, _context2.t0)(_context2.t1);
            case 9:
            case "end":
              return _context2.stop();
          }
        }, _callee2);
      }));
      return _getExtensions.apply(this, arguments);
    }
  }, [extension.extensionProvider]);
  var nodeAdf = React.useMemo(function () {
    return nodeToJSON(node);
  }, [node]);
  var extensionItems = React.useMemo(function () {
    if (!extension.extensionApi) {
      return [];
    }
    return getContextualToolbarItemsFromModule(extensions, nodeAdf, extension.extensionApi);
  }, [extensions, nodeAdf, extension.extensionApi]);
  if (!extensionItems.length || !dropdownOptions) {
    return null;
  }
  return /*#__PURE__*/React.createElement(React.Fragment, null, extensionItems.map(function (item, _idx) {
    if (!('key' in item)) {
      return null;
    }
    return /*#__PURE__*/React.createElement(DropdownMenuExtensionItem, {
      key: item.key,
      item: item,
      editorView: editorView,
      disabled: disabled,
      node: node,
      extension: extension,
      dropdownOptions: dropdownOptions
    });
  }), areAnyNewToolbarFlagsEnabled && /*#__PURE__*/React.createElement(DropdownSeparator, null));
};