import React, {memo, useCallback, useMemo} from 'react';
import {View} from 'react-native';
import {
  InternalRendererProps,
  TBlock,
  useContentWidth,
  useInternalRenderer,
  useRendererProps,
} from 'react-native-render-html';
import {ImageModal} from '@components/_core/Image';
import {useModalHandler} from '@hooks/useModalHandler';
import {openUrlFromApp} from '@shared/utils';

import {getResizedAndAlignStyle} from '../../utils';
import {styles} from './styles';
import {getParentLink} from './utils';

function CustomImageRenderer(props: InternalRendererProps<TBlock>) {
  const {Renderer, rendererProps} = useInternalRenderer('img', props);
  const customRendererProps = useRendererProps('img');
  const contentWidth = useContentWidth();
  const {isVisible, onOpenModal, onCloseModal} = useModalHandler();
  const shouldResizeAndAlign = (customRendererProps as any)
    .resizeAndAlignMultimedia;

  const onPress = useCallback(() => {
    const parentLink = getParentLink(props.tnode);
    const parentLinkUrl: string | undefined = parentLink?.attributes?.href;

    if (parentLinkUrl) {
      openUrlFromApp(parentLinkUrl);
    } else {
      onOpenModal();
    }
  }, [onOpenModal, props.tnode]);

  const imageStyle = useMemo(() => {
    if (shouldResizeAndAlign) {
      const style = getResizedAndAlignStyle(props.tnode, contentWidth);
      return style?.width ? {...style, height: undefined} : {};
    }

    return rendererProps.style || {};
  }, [shouldResizeAndAlign, rendererProps.style, contentWidth, props.tnode]);

  return (
    <View style={[styles.container, imageStyle && {width: contentWidth}]}>
      <Renderer {...rendererProps} onPress={onPress} style={imageStyle} />
      {!!rendererProps.source.uri && (
        <ImageModal
          withAuthHeader
          source={{uri: rendererProps.source.uri}}
          showZoom={isVisible}
          onClose={onCloseModal}
        />
      )}
    </View>
  );
}

export default memo(CustomImageRenderer);
