/** @jsx jsx */
import { Fragment, useMemo } from 'react';
import { jsx } from '@emotion/react';
import { getRandomHex } from '@atlaskit/media-common';
import { useFilePreview } from '@atlaskit/media-file-preview';
import { MediaImage } from '@atlaskit/media-ui';
import { InlineImageCardLoadingView } from './views/loading-view';
export const InlineImageCard = ({
  dimensions,
  identifier,
  renderError,
  alt,
  isLazy,
  ssr,
  crop,
  stretch
}) => {
  // Generate unique traceId for file
  const traceContext = useMemo(() => ({
    traceId: getRandomHex(8)
  }), []);

  // TODO do we need to handle nonCriticalError
  const {
    preview,
    error: previewError,
    onImageError,
    onImageLoad,
    getSsrScriptProps
  } = useFilePreview({
    identifier,
    ssr,
    dimensions,
    traceContext
  });
  if (previewError) {
    return renderError({
      error: previewError
    });
  }
  if (!preview) {
    return jsx(InlineImageCardLoadingView, null);
  }
  return jsx(Fragment, null, jsx(MediaImage, {
    dataURI: preview.dataURI,
    alt: alt,
    previewOrientation: preview.orientation,
    onImageLoad: () => {
      onImageLoad(preview);
    },
    onImageError: onImageError,
    loading: isLazy ? 'lazy' : undefined,
    forceSyncDisplay: !!ssr,
    crop: crop,
    stretch: stretch
  }), getSsrScriptProps && jsx("script", getSsrScriptProps()));
};