import React, { lazy, Suspense, useCallback, useEffect, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { di } from 'react-magnetic-di';
// eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
import uuid from 'uuid';
import { useAnalyticsEvents } from '../../common/analytics/generated/use-analytics-events';
import { failUfoExperience, startUfoExperience } from '../../state/analytics';
import { importWithRetry } from '../../utils';
import { useSmartLinkAnalyticsContext } from '../../utils/analytics/SmartLinkAnalyticsContext';
import { isFlexibleUiCard } from '../../utils/flexible';
import { clearMarks, clearMeasures } from '../../utils/performance';
import { LoadingCardLink } from './component-lazy/LoadingCardLink';
export const LazyCardWithUrlContent = /*#__PURE__*/lazy(() => importWithRetry(() => import( /* webpackChunkName: "@atlaskit-internal_smartcard-urlcardcontent" */'./component-lazy/index')));
export function CardWithURLRenderer(props) {
  // eslint-disable-next-line @atlaskit/platform/prefer-crypto-random-uuid -- Use crypto.randomUUID instead
  const [id] = useState(() => props.id ? props.id : uuid());
  const {
    fireEvent
  } = useAnalyticsEvents();
  useEffect(() => {
    // ComponentWillUnmount
    return () => {
      clearMarks(id);
      clearMeasures(id);
    };
  }, [id]);
  const {
    url,
    appearance,
    isSelected,
    isHovered,
    frameStyle,
    onClick,
    container,
    onResolve,
    onError,
    testId,
    actionOptions,
    inheritDimensions,
    platform,
    embedIframeRef,
    embedIframeUrlType,
    inlinePreloaderStyle,
    children,
    ui,
    showHoverPreview,
    hoverPreviewOptions,
    placeholder,
    fallbackComponent,
    removeTextHighlightingFromTitle,
    resolvingPlaceholder,
    truncateInline,
    CompetitorPrompt,
    disablePreviewPanel
  } = props;
  const isFlexibleUi = isFlexibleUiCard(children, ui);
  const analyticsContext = useSmartLinkAnalyticsContext({
    display: isFlexibleUi ? 'flexible' : appearance,
    id,
    url: url !== null && url !== void 0 ? url : ''
  });
  const errorHandler = useCallback((error, info) => {
    const {
      componentStack
    } = info;
    const errorInfo = {
      componentStack
    };
    // NB: APIErrors are thrown in response to Object Resolver Service. We do not
    // fire an event for these, as they do not cover failed UI render events.
    // The rest of the errors caught here are unexpected, and correlate
    // to the reliability of the smart-card front-end components.
    // Likewise, chunk loading errors are not caused by a failure of smart-card rendering.
    if (error.name === 'ChunkLoadError') {
      fireEvent('operational.smartLink.chunkLoadFailed', {
        ...(analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes),
        display: appearance,
        error: error,
        errorInfo: errorInfo,
        definitionId: null
      });
    } else if (error.name !== 'APIError') {
      startUfoExperience('smart-link-rendered', id || 'NULL');
      failUfoExperience('smart-link-rendered', id || 'NULL');
      failUfoExperience('smart-link-authenticated', id || 'NULL');
      fireEvent('ui.smartLink.renderFailed', {
        ...(analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes),
        display: isFlexibleUi ? 'flexible' : appearance,
        id: id !== null && id !== void 0 ? id : null,
        error: error,
        errorInfo: errorInfo
      });
    }
    onError && onError({
      status: 'errored',
      url: url !== null && url !== void 0 ? url : '',
      err: error
    });
  }, [analyticsContext === null || analyticsContext === void 0 ? void 0 : analyticsContext.attributes, appearance, fireEvent, id, isFlexibleUi, onError, url]);
  if (!url) {
    throw new Error('@atlaskit/smart-card: url property is missing.');
  }
  const defaultFallBackComponent = () => null;
  const FallbackComponent = fallbackComponent !== null && fallbackComponent !== void 0 ? fallbackComponent : defaultFallBackComponent;
  const ErrorFallback = () => /*#__PURE__*/React.createElement(FallbackComponent, null);
  const cardWithUrlProps = {
    id,
    url,
    appearance,
    onClick,
    isSelected,
    isHovered,
    frameStyle,
    container,
    onResolve,
    onError,
    testId,
    actionOptions,
    inheritDimensions,
    platform,
    embedIframeRef,
    embedIframeUrlType,
    inlinePreloaderStyle,
    ui,
    showHoverPreview,
    hoverPreviewOptions,
    placeholder,
    removeTextHighlightingFromTitle,
    resolvingPlaceholder,
    truncateInline,
    CompetitorPrompt,
    disablePreviewPanel
  };
  return /*#__PURE__*/React.createElement(ErrorBoundary, {
    FallbackComponent: ErrorFallback,
    onError: errorHandler
  }, /*#__PURE__*/React.createElement(Suspense, {
    fallback: /*#__PURE__*/React.createElement(LoadingCardLink, cardWithUrlProps)
  }, /*#__PURE__*/React.createElement(LazyCardWithUrlContent, cardWithUrlProps, children)));
}