import _extends from "@babel/runtime/helpers/extends";
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { AnalyticsContext, useAnalyticsEvents as useAnalyticsEventsNext } from '@atlaskit/analytics-next';
import { useSmartLinkContext } from '@atlaskit/link-provider';
import { fg } from '@atlaskit/platform-feature-flags';
import { componentWithCondition, functionUnionWithCondition } from '@atlaskit/platform-feature-flags-react';
import { expValEquals } from '@atlaskit/tmp-editor-statsig/exp-val-equals';
import { expValEqualsNoExposure } from '@atlaskit/tmp-editor-statsig/exp-val-equals-no-exposure';
import { useAnalyticsEvents } from '../../../common/analytics/generated/use-analytics-events';
import { CardDisplay, SmartLinkPosition, SmartLinkSize } from '../../../constants';
import extractRovoChatAction from '../../../extractors/flexible/actions/extract-rovo-chat-action';
import { getDefinitionId, getExtensionKey, getServices } from '../../../state/helpers';
import useInlineActionNudgeExperiment from '../../../state/hooks/use-inline-action-nudge-experiment';
import useRovoConfig from '../../../state/hooks/use-rovo-config';
import { useSmartCardState } from '../../../state/store';
import { isSpecialEvent } from '../../../utils';
import { getIsAISummaryEnabled } from '../../../utils/ai-summary';
import { fireLinkClickedEvent } from '../../../utils/analytics/click';
import { flexibleUiOptions } from '../styled';
import { getMetadata } from '../utils';
import ContentContainer from './ContentContainer';
import HoverCardForbiddenView from './views/forbidden';
import HoverCardResolvedView from './views/resolved';
import HoverCardLoadingView from './views/resolving';
import HoverCardUnauthorisedView from './views/unauthorised';
import RovoUnauthorisedView from './views/unauthorised/RovoUnauthorisedView';
export const hoverCardClassName = 'smart-links-hover-preview';
const useIsResolvedView = ({
  cardState,
  hoverPreviewOptions
}) => {
  var _hoverPreviewOptions$;
  return !(hoverPreviewOptions !== null && hoverPreviewOptions !== void 0 && (_hoverPreviewOptions$ = hoverPreviewOptions.render) !== null && _hoverPreviewOptions$ !== void 0 && _hoverPreviewOptions$.call(hoverPreviewOptions)) && cardState.status === 'resolved';
};
const useServices = ({
  url
}) => {
  const linkState = useSmartCardState(url);
  const services = getServices(linkState.details);
  return services;
};
const useIsUnauthorisedView = ({
  cardState,
  url,
  hoverPreviewOptions
}) => {
  var _hoverPreviewOptions$2;
  const services = useServices({
    url
  });
  return !(hoverPreviewOptions !== null && hoverPreviewOptions !== void 0 && (_hoverPreviewOptions$2 = hoverPreviewOptions.render) !== null && _hoverPreviewOptions$2 !== void 0 && _hoverPreviewOptions$2.call(hoverPreviewOptions)) && cardState.status === 'unauthorized' && Boolean(services === null || services === void 0 ? void 0 : services.length);
};
const useIsShowPreauthBetterHovercard = props => {
  const {
    rovoOptions: rovoConfig
  } = useRovoConfig();
  return Boolean(useIsUnauthorisedView(props) && (rovoConfig === null || rovoConfig === void 0 ? void 0 : rovoConfig.isRovoEnabled) && expValEquals('platform_sl_3p_preauth_better_hovercard', 'isEnabled', true));
};
const HoverCardContent = ({
  id = '',
  cardState,
  onActionClick,
  onResolve,
  renderers,
  url,
  onMouseEnter,
  onMouseLeave,
  onDismiss,
  actionOptions,
  hoverPreviewOptions,
  showRovoResolvedView
}) => {
  var _linkState$status, _cardState$details;
  const {
    createAnalyticsEvent
  } = useAnalyticsEventsNext();
  const {
    fireEvent
  } = useAnalyticsEvents();
  const extensionKey = useMemo(() => getExtensionKey(cardState.details), [cardState.details]);
  const linkState = useSmartCardState(url);
  const linkStatus = (_linkState$status = linkState.status) !== null && _linkState$status !== void 0 ? _linkState$status : 'pending';
  const definitionId = useMemo(() => getDefinitionId(cardState.details), [cardState.details]);
  const {
    isAdminHubAIEnabled,
    product
  } = useSmartLinkContext();
  const isAISummaryEnabled = getIsAISummaryEnabled(isAdminHubAIEnabled, cardState.details);
  const services = getServices(linkState.details);
  const statusRef = useRef(linkStatus);
  const fireEventRef = useRef(fireEvent);
  const definitionIdRef = useRef(definitionId);
  useEffect(() => {
    /**
     * Must access object value via ref because its not stable
     * and it can trigger useEffect to re-run below
     */
    if (statusRef.current !== linkStatus) {
      statusRef.current = linkStatus;
    }
    if (fireEventRef.current !== fireEvent) {
      fireEventRef.current = fireEvent;
    }
    if (definitionIdRef.current !== definitionId) {
      definitionIdRef.current = definitionId;
    }
  }, [linkStatus, fireEvent, definitionId]);
  useEffect(() => {
    var _definitionIdRef$curr;
    const previewDisplay = 'card';
    const previewInvokeMethod = 'mouse_hover';
    const cardOpenTime = Date.now();
    const fireEventCurrent = fireEventRef.current;
    fireEventCurrent('ui.hoverCard.viewed', {
      previewDisplay,
      previewInvokeMethod,
      definitionId: (_definitionIdRef$curr = definitionIdRef.current) !== null && _definitionIdRef$curr !== void 0 ? _definitionIdRef$curr : null
    });
    return () => {
      var _definitionIdRef$curr2;
      const hoverTime = Date.now() - cardOpenTime;
      fireEventCurrent('ui.hoverCard.dismissed', {
        previewDisplay,
        previewInvokeMethod,
        hoverTime,
        definitionId: (_definitionIdRef$curr2 = definitionIdRef.current) !== null && _definitionIdRef$curr2 !== void 0 ? _definitionIdRef$curr2 : null
      });
    };
  }, []);
  const onClick = useCallback(event => {
    const isModifierKeyPressed = isSpecialEvent(event);
    fireEvent('ui.smartLink.clicked.titleGoToLink', {
      id,
      display: CardDisplay.HoverCardPreview,
      isModifierKeyPressed,
      definitionId: definitionId !== null && definitionId !== void 0 ? definitionId : null
    });
    fireLinkClickedEvent(createAnalyticsEvent)(event);
  }, [createAnalyticsEvent, id, fireEvent, definitionId]);
  const data = (_cardState$details = cardState.details) === null || _cardState$details === void 0 ? void 0 : _cardState$details.data;
  const {
    subtitle
  } = getMetadata(extensionKey, data);
  const titleMaxLines = subtitle && subtitle.length > 0 ? 1 : 2;

  // Platform apps (Home, Goals, Projects, and Teams) should by default open in the same tab when the FF is enabled.
  const isSameTabAlignmentEnabled = fg('townsquare-same-tab-alignment-gcko-849');
  const anchorTarget = product === 'ATLAS' && isSameTabAlignmentEnabled ? '_self' : undefined;
  const titleBlockProps = {
    maxLines: titleMaxLines,
    size: SmartLinkSize.Large,
    position: SmartLinkPosition.Center,
    subtitle: subtitle,
    ...(isSameTabAlignmentEnabled ? {
      anchorTarget
    } : undefined)
  };
  const uiOptions = flexibleUiOptions;
  uiOptions.enableSnippetRenderer = true;
  const flexibleCardProps = {
    appearance: CardDisplay.HoverCardPreview,
    cardState: cardState,
    onClick: onClick,
    onResolve: onResolve,
    origin: 'smartLinkPreviewHoverCard',
    renderers: renderers,
    actionOptions,
    ui: uiOptions,
    url: url,
    children: null
  };
  const onClickStopPropagation = useCallback(e => e.stopPropagation(), []);
  const useIsResolvedViewGated = functionUnionWithCondition(() => fg('platform_sl_3p_preauth_better_hovercard_killswitch'), useIsResolvedView, () => undefined);
  const useIsUnauthorisedViewGated = functionUnionWithCondition(() => fg('platform_sl_3p_preauth_better_hovercard_killswitch'), useIsUnauthorisedView, () => undefined);
  const useIsShowPreauthBetterHovercardGated = functionUnionWithCondition(() => fg('platform_sl_3p_preauth_better_hovercard_killswitch'), useIsShowPreauthBetterHovercard, () => undefined);
  const isResolved = useIsResolvedViewGated({
    cardState,
    hoverPreviewOptions
  });
  const isUnauthorised = useIsUnauthorisedViewGated({
    cardState,
    url,
    hoverPreviewOptions
  });
  const showPreauthBetterHovercard = useIsShowPreauthBetterHovercardGated({
    cardState,
    url,
    hoverPreviewOptions
  });
  if (fg('platform_sl_3p_preauth_better_hovercard_killswitch')) {
    const cardView = (_hoverPreviewOptions$3 => {
      const overrideView = hoverPreviewOptions === null || hoverPreviewOptions === void 0 ? void 0 : (_hoverPreviewOptions$3 = hoverPreviewOptions.render) === null || _hoverPreviewOptions$3 === void 0 ? void 0 : _hoverPreviewOptions$3.call(hoverPreviewOptions);
      if (overrideView) {
        return overrideView;
      }
      if (cardState.status === 'errored') {
        return null;
      }
      if (cardState.status === 'resolving' || cardState.metadataStatus === 'pending') {
        return /*#__PURE__*/React.createElement(HoverCardLoadingView, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (isUnauthorised) {
        if (showPreauthBetterHovercard) {
          return /*#__PURE__*/React.createElement(RovoUnauthorisedView, {
            extensionKey: extensionKey,
            id: id,
            flexibleCardProps: flexibleCardProps,
            onDismiss: onDismiss,
            url: url
          });
        }
        return /*#__PURE__*/React.createElement(HoverCardUnauthorisedView, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/React.createElement(HoverCardForbiddenView, {
          flexibleCardProps: flexibleCardProps
        });
      }
      const is3PInlinePostAuthActionsEnabled = fg('rovogrowth-640-inline-action-nudge-fg') && expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true);
      if (isResolved) {
        return /*#__PURE__*/React.createElement(HoverCardResolvedView, _extends({}, fg('platform_sl_3p_auth_rovo_action_kill_switch') || is3PInlinePostAuthActionsEnabled ? {
          actionOptions,
          showRovoResolvedView
        } : undefined, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        }));
      }
      return null;
    })();
    return cardView ? /*#__PURE__*/React.createElement(ContentContainer, {
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClickStopPropagation,
      widthAppearance: showPreauthBetterHovercard ? 'slim' : undefined,
      isAIEnabled: isAISummaryEnabled,
      url: url
    }, cardView) : null;
  } else {
    const getCardView = cardState => {
      var _hoverPreviewOptions$4;
      const overrideView = hoverPreviewOptions === null || hoverPreviewOptions === void 0 ? void 0 : (_hoverPreviewOptions$4 = hoverPreviewOptions.render) === null || _hoverPreviewOptions$4 === void 0 ? void 0 : _hoverPreviewOptions$4.call(hoverPreviewOptions);
      if (overrideView) {
        return overrideView;
      }
      if (cardState.status === 'errored') {
        return null;
      }
      if (cardState.status === 'resolving' || cardState.metadataStatus === 'pending') {
        return /*#__PURE__*/React.createElement(HoverCardLoadingView, {
          flexibleCardProps: flexibleCardProps,
          titleBlockProps: titleBlockProps
        });
      }
      if (cardState.status === 'unauthorized' && services !== null && services !== void 0 && services.length) {
        return /*#__PURE__*/React.createElement(HoverCardUnauthorisedView, {
          extensionKey: extensionKey,
          id: id,
          flexibleCardProps: flexibleCardProps,
          url: url
        });
      }
      if (cardState.status === 'forbidden' || cardState.status === 'not_found') {
        return /*#__PURE__*/React.createElement(HoverCardForbiddenView, {
          flexibleCardProps: flexibleCardProps
        });
      }
      const is3PInlinePostAuthActionsEnabled = fg('rovogrowth-640-inline-action-nudge-fg') && expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true);
      if (cardState.status === 'resolved') {
        return /*#__PURE__*/React.createElement(HoverCardResolvedView, _extends({}, fg('platform_sl_3p_auth_rovo_action_kill_switch') || is3PInlinePostAuthActionsEnabled ? {
          actionOptions,
          showRovoResolvedView
        } : undefined, {
          cardState: cardState,
          extensionKey: extensionKey,
          flexibleCardProps: flexibleCardProps,
          isAISummaryEnabled: isAISummaryEnabled,
          onActionClick: onActionClick,
          titleBlockProps: titleBlockProps
        }));
      }
      return null;
    };
    const cardView = getCardView(cardState);
    return cardView ? /*#__PURE__*/React.createElement(ContentContainer, {
      onMouseEnter: onMouseEnter,
      onMouseLeave: onMouseLeave,
      onClick: onClickStopPropagation,
      isAIEnabled: isAISummaryEnabled,
      url: url
    }, cardView) : null;
  }
};
const HoverCardContentWithViewVariant = props => {
  const {
    cardState,
    actionOptions,
    url
  } = props;
  const rovoConfig = useRovoConfig();
  const isResolved = useIsResolvedView(props);
  const showPreauthBetterHovercard = useIsShowPreauthBetterHovercard(props);
  const showRovoResolvedView = useMemo(() => isResolved && cardState.details && extractRovoChatAction({
    response: cardState.details,
    rovoConfig,
    actionOptions
  }) !== undefined, [actionOptions, cardState.details, rovoConfig, isResolved]);
  const {
    isEnabled: rovoActionsCtaShown
  } = useInlineActionNudgeExperiment(url, true, actionOptions);
  const data = useMemo(() => {
    let viewVariant = 'default';
    if (showRovoResolvedView && (expValEqualsNoExposure('platform_sl_3p_auth_rovo_action', 'isEnabled', true) || expValEqualsNoExposure('rovogrowth-640-inline-action-nudge-exp', 'isEnabled', true))) {
      viewVariant = 'rovo-resolved-view';
    } else if (showPreauthBetterHovercard) {
      viewVariant = 'rovo-unauthorised-view';
    }
    return {
      attributes: {
        viewVariant,
        rovoActionsCtaShown
      }
    };
  }, [showRovoResolvedView, showPreauthBetterHovercard, rovoActionsCtaShown]);
  return /*#__PURE__*/React.createElement(AnalyticsContext, {
    data: data
  }, /*#__PURE__*/React.createElement(HoverCardContent, _extends({}, props, {
    showRovoResolvedView: showRovoResolvedView
  })));
};
const _default_1 = componentWithCondition(() => {
  // We need to read both of them to sutisfy some of the tests that expect both to be checked.
  const flagA = fg('platform_sl_3p_preauth_better_hovercard_killswitch');
  const flagB = fg('platform_sl_3p_auth_rovo_action_kill_switch');
  const flagC = fg('rovogrowth-640-inline-action-nudge-fg');
  return flagA || flagB || flagC;
}, HoverCardContentWithViewVariant, HoverCardContent);
export default _default_1;