import _extends from "@babel/runtime/helpers/extends";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import DropdownMenu from '@atlaskit/dropdown-menu';
import { fg } from '@atlaskit/platform-feature-flags';
import { useAnalyticsEvents } from '../../../../../../../common/analytics/generated/use-analytics-events';
import extractLozengeActionItems from '../../../../../../../extractors/action/extract-lozenge-action-items';
import useInvoke from '../../../../../../../state/hooks/use-invoke';
import { isInvokeCustomError } from '../../../../../../../state/hooks/use-invoke/utils';
import useResolve from '../../../../../../../state/hooks/use-resolve';
import createStatusUpdateRequest from '../../../../../../../utils/actions/create-status-update-request';
import { TrackQuickActionType } from '../../../../../../../utils/analytics/analytics';
import withErrorBoundary from './error-boundary';
import { permissionLoadErrorAnalyticsPayload, unknownLoadErrorAnalyticsPayload, unknownUpdateErrorAnalyticsPayload, validationUpdateErrorAnalyticsPayload } from './lozenge-action-analytics';
import LozengeActionError from './lozenge-action-error';
import { LozengeActionErrorMessages } from './lozenge-action-error/types';
import LozengeActionItemsGroup from './lozenge-action-items-group';
import LozengeActionTrigger from './lozenge-action-trigger';
var validateItems = function validateItems() {
  var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var text = arguments.length > 1 ? arguments[1] : undefined;
  return items.filter(function (item) {
    return item.text !== text;
  });
};
var LozengeAction = function LozengeAction(_ref) {
  var _action$update;
  var action = _ref.action,
    appearance = _ref.appearance,
    _ref$testId = _ref.testId,
    testId = _ref$testId === void 0 ? 'smart-element-lozenge-action' : _ref$testId,
    text = _ref.text,
    zIndex = _ref.zIndex,
    onAfterChanged = _ref.onAfterChanged;
  var _useState = useState({
      appearance: appearance,
      text: text
    }),
    _useState2 = _slicedToArray(_useState, 2),
    selected = _useState2[0],
    setSelected = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isLoaded = _useState4[0],
    setIsLoaded = _useState4[1];
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    isLoading = _useState6[0],
    setIsLoading = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    isOpen = _useState8[0],
    setIsOpen = _useState8[1];
  var _useState9 = useState(),
    _useState0 = _slicedToArray(_useState9, 2),
    items = _useState0[0],
    setItems = _useState0[1];
  var _useState1 = useState(),
    _useState10 = _slicedToArray(_useState1, 2),
    errorMessage = _useState10[0],
    setErrorMessage = _useState10[1];
  var reload = useResolve();
  var invoke = useInvoke();
  var _useAnalyticsEvents = useAnalyticsEvents(),
    fireEvent = _useAnalyticsEvents.fireEvent;
  useEffect(function () {
    setSelected({
      text: text,
      appearance: appearance
    });
  }, [text, appearance]);
  var _ref2 = (action === null || action === void 0 || (_action$update = action.update) === null || _action$update === void 0 ? void 0 : _action$update.details) || {},
    url = _ref2.url,
    linkId = _ref2.id,
    invokePreviewAction = _ref2.invokePreviewAction;
  var handleOpenChange = useCallback( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(args) {
      var responseItems, validItems;
      return _regeneratorRuntime.wrap(function _callee$(_context) {
        while (1) switch (_context.prev = _context.next) {
          case 0:
            setIsOpen(args.isOpen);
            if (!args.isOpen) {
              _context.next = 24;
              break;
            }
            fireEvent('ui.button.clicked.smartLinkStatusLozenge', {});
            fireEvent('track.smartLinkQuickAction.started', {
              smartLinkActionType: TrackQuickActionType.StatusUpdate
            });
            if (!(!isLoaded && action !== null && action !== void 0 && action.read)) {
              _context.next = 24;
              break;
            }
            _context.prev = 5;
            setIsLoading(true);
            _context.next = 9;
            return invoke(action.read, extractLozengeActionItems);
          case 9:
            responseItems = _context.sent;
            validItems = typeof text === 'string' ? validateItems(responseItems, text) : responseItems;
            setItems(validItems);
            setIsLoaded(true);
            if ((validItems === null || validItems === void 0 ? void 0 : validItems.length) === 0) {
              fireEvent('track.smartLinkQuickAction.failed', permissionLoadErrorAnalyticsPayload);
              setErrorMessage(fg('confluence-issue-terminology-refresh') ? LozengeActionErrorMessages.noDataIssueTermRefresh : LozengeActionErrorMessages.noData);
              setIsLoaded(false);
            }
            _context.next = 21;
            break;
          case 16:
            _context.prev = 16;
            _context.t0 = _context["catch"](5);
            setErrorMessage(LozengeActionErrorMessages.unknown);
            setIsLoaded(false);
            fireEvent('track.smartLinkQuickAction.failed', unknownLoadErrorAnalyticsPayload);
          case 21:
            _context.prev = 21;
            setIsLoading(false);
            return _context.finish(21);
          case 24:
            if (!args.isOpen) {
              setErrorMessage(undefined);
            }
          case 25:
          case "end":
            return _context.stop();
        }
      }, _callee, null, [[5, 16, 21, 24]]);
    }));
    return function (_x) {
      return _ref3.apply(this, arguments);
    };
  }(), [action.read, invoke, isLoaded, text, fireEvent]);
  var trigger = useCallback(function (props) {
    return /*#__PURE__*/React.createElement(LozengeActionTrigger, _extends({}, props, {
      appearance: selected.appearance,
      isOpen: isOpen,
      testId: testId,
      text: selected.text
    }));
  }, [selected.appearance, selected.text, isOpen, testId]);
  var handleItemClick = useCallback( /*#__PURE__*/function () {
    var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(id, text, appearance) {
      var updateAction, request;
      return _regeneratorRuntime.wrap(function _callee2$(_context2) {
        while (1) switch (_context2.prev = _context2.next) {
          case 0:
            _context2.prev = 0;
            fireEvent('ui.button.clicked.smartLinkStatusListItem', {});
            updateAction = action === null || action === void 0 ? void 0 : action.update;
            if (!(updateAction && id)) {
              _context2.next = 18;
              break;
            }
            setIsLoading(true);
            request = createStatusUpdateRequest(updateAction, id);
            _context2.next = 8;
            return invoke(request);
          case 8:
            onAfterChanged === null || onAfterChanged === void 0 || onAfterChanged();
            setSelected({
              appearance: appearance,
              text: text
            });
            setIsLoading(false);
            setIsLoaded(false);
            setIsOpen(false);
            setItems([]);
            fireEvent('track.smartLinkQuickAction.success', {
              smartLinkActionType: TrackQuickActionType.StatusUpdate
            });
            if (!url) {
              _context2.next = 18;
              break;
            }
            _context2.next = 18;
            return reload(url, true, undefined, linkId);
          case 18:
            _context2.next = 24;
            break;
          case 20:
            _context2.prev = 20;
            _context2.t0 = _context2["catch"](0);
            setIsLoading(false);
            if (isInvokeCustomError(_context2.t0)) {
              setErrorMessage(_context2.t0.message);
              fireEvent('track.smartLinkQuickAction.failed', validationUpdateErrorAnalyticsPayload);
            } else {
              setErrorMessage(LozengeActionErrorMessages.updateFailed);
              fireEvent('track.smartLinkQuickAction.failed', unknownUpdateErrorAnalyticsPayload);
            }
          case 24:
          case "end":
            return _context2.stop();
        }
      }, _callee2, null, [[0, 20]]);
    }));
    return function (_x2, _x3, _x4) {
      return _ref4.apply(this, arguments);
    };
  }(), [action === null || action === void 0 ? void 0 : action.update, invoke, linkId, reload, url, fireEvent, onAfterChanged]);
  var dropdownItemGroup = useMemo(function () {
    if (errorMessage) {
      return /*#__PURE__*/React.createElement(LozengeActionError, {
        errorMessage: errorMessage,
        testId: testId,
        url: url,
        invokePreviewAction: invokePreviewAction
      });
    }
    if (items && items.length > 0) {
      return /*#__PURE__*/React.createElement(LozengeActionItemsGroup, {
        testId: testId,
        items: items,
        onClick: handleItemClick
      });
    }
  }, [errorMessage, handleItemClick, items, invokePreviewAction, testId, url]);
  return /*#__PURE__*/React.createElement(DropdownMenu, _extends({
    isLoading: isLoading,
    isOpen: isOpen,
    onOpenChange: handleOpenChange,
    testId: testId,
    trigger: trigger,
    zIndex: zIndex
  }, fg('lozenge-dropdown-prop-should-render-to-parent') ? {
    shouldRenderToParent: true
  } : {}), dropdownItemGroup);
};
export default withErrorBoundary(LozengeAction);