import React, { useCallback, useRef, useState } from 'react';
import { extractSmartLinkPreviewImage } from '../../../extractors/flexible/extract-preview';
import { PreviewBlock } from '../../FlexibleCard/components/blocks';
const ImagePreview = ({
  fallbackElementHeight,
  response
}) => {
  const transitionStarted = useRef(false);
  const previewBlockRef = useRef(null);
  const [showPreview, setShowPreview] = useState(true);
  const [dynamicStyles, setDynamicStyles] = useState({});

  // Set Preview to a fixed height to enable transitions
  const onPreviewRender = useCallback(() => {
    if (previewBlockRef.current) {
      var _previewBlockRef$curr;
      const previewHeight = (_previewBlockRef$curr = previewBlockRef.current) === null || _previewBlockRef$curr === void 0 ? void 0 : _previewBlockRef$curr.getBoundingClientRect().height;
      setDynamicStyles({
        borderTopLeftRadius: "var(--ds-radius-large, 8px)",
        borderTopRightRadius: "var(--ds-radius-large, 8px)",
        ...(previewHeight ? {
          height: `${previewHeight}px`
        } : {})
      });
    }
  }, []);

  // On error set Preview to Fallback height with transition
  const onPreviewError = useCallback(() => {
    if (transitionStarted.current === false) {
      setDynamicStyles({
        transition: 'height 300ms ease-in-out',
        height: `${fallbackElementHeight}px`
      });
      transitionStarted.current = true;
    }
  }, [fallbackElementHeight]);
  const onPreviewTransitionEnd = useCallback(() => {
    setShowPreview(false);
  }, []);
  return showPreview && extractSmartLinkPreviewImage(response) ? /*#__PURE__*/React.createElement(PreviewBlock, {
    onError: onPreviewError,
    ignoreContainerPadding: true,
    onTransitionEnd: onPreviewTransitionEnd,
    blockRef: previewBlockRef,
    onRender: onPreviewRender
    // eslint-disable-next-line @atlaskit/ui-styling-standard/enforce-style-prop
    ,
    style: dynamicStyles
  }) : null;
};
export default ImagePreview;