import _extends from "@babel/runtime/helpers/extends";
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';
const validateItems = (items = [], text) => {
  return items.filter(item => item.text !== text);
};
const LozengeAction = ({
  action,
  appearance,
  testId = 'smart-element-lozenge-action',
  text,
  zIndex,
  onAfterChanged
}) => {
  var _action$update;
  const [selected, setSelected] = useState({
    appearance,
    text
  });
  const [isLoaded, setIsLoaded] = useState(false);
  const [isLoading, setIsLoading] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [items, setItems] = useState();
  const [errorMessage, setErrorMessage] = useState();
  const reload = useResolve();
  const invoke = useInvoke();
  const {
    fireEvent
  } = useAnalyticsEvents();
  useEffect(() => {
    setSelected({
      text,
      appearance
    });
  }, [text, appearance]);
  const {
    url,
    id: linkId,
    invokePreviewAction
  } = (action === null || action === void 0 ? void 0 : (_action$update = action.update) === null || _action$update === void 0 ? void 0 : _action$update.details) || {};
  const handleOpenChange = useCallback(async args => {
    setIsOpen(args.isOpen);
    if (args.isOpen) {
      fireEvent('ui.button.clicked.smartLinkStatusLozenge', {});
      fireEvent('track.smartLinkQuickAction.started', {
        smartLinkActionType: TrackQuickActionType.StatusUpdate
      });
      if (!isLoaded && action !== null && action !== void 0 && action.read) {
        try {
          setIsLoading(true);
          const responseItems = await invoke(action.read, extractLozengeActionItems);
          const 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);
          }
        } catch {
          setErrorMessage(LozengeActionErrorMessages.unknown);
          setIsLoaded(false);
          fireEvent('track.smartLinkQuickAction.failed', unknownLoadErrorAnalyticsPayload);
        } finally {
          setIsLoading(false);
        }
      }
    }
    if (!args.isOpen) {
      setErrorMessage(undefined);
    }
  }, [action.read, invoke, isLoaded, text, fireEvent]);
  const trigger = useCallback(props => /*#__PURE__*/React.createElement(LozengeActionTrigger, _extends({}, props, {
    appearance: selected.appearance,
    isOpen: isOpen,
    testId: testId,
    text: selected.text
  })), [selected.appearance, selected.text, isOpen, testId]);
  const handleItemClick = useCallback(async (id, text, appearance) => {
    try {
      fireEvent('ui.button.clicked.smartLinkStatusListItem', {});
      const updateAction = action === null || action === void 0 ? void 0 : action.update;
      if (updateAction && id) {
        setIsLoading(true);
        const request = createStatusUpdateRequest(updateAction, id);
        await invoke(request);
        onAfterChanged === null || onAfterChanged === void 0 ? void 0 : onAfterChanged();
        setSelected({
          appearance,
          text
        });
        setIsLoading(false);
        setIsLoaded(false);
        setIsOpen(false);
        setItems([]);
        fireEvent('track.smartLinkQuickAction.success', {
          smartLinkActionType: TrackQuickActionType.StatusUpdate
        });
        if (url) {
          await reload(url, true, undefined, linkId);
        }
      }
    } catch (err) {
      setIsLoading(false);
      if (isInvokeCustomError(err)) {
        setErrorMessage(err.message);
        fireEvent('track.smartLinkQuickAction.failed', validationUpdateErrorAnalyticsPayload);
      } else {
        setErrorMessage(LozengeActionErrorMessages.updateFailed);
        fireEvent('track.smartLinkQuickAction.failed', unknownUpdateErrorAnalyticsPayload);
      }
    }
  }, [action === null || action === void 0 ? void 0 : action.update, invoke, linkId, reload, url, fireEvent, onAfterChanged]);
  const dropdownItemGroup = useMemo(() => {
    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, {
    isLoading: isLoading,
    isOpen: isOpen,
    onOpenChange: handleOpenChange,
    testId: testId,
    trigger: trigger,
    zIndex: zIndex,
    shouldRenderToParent: true
  }, dropdownItemGroup);
};
export default withErrorBoundary(LozengeAction);