import * as React from 'react';
import { Image, Linking, Text, TouchableOpacity, View } from 'react-native';
import { useStyles } from './styles';
import { getPreviewData } from './utils';
import RenderTextWithMention from '../RenderTextWithMention/RenderTextWithMention';
export const LinkPreview = /*#__PURE__*/React.memo(({
  text,
  mentionPositionArr
}) => {
  const [data, setData] = React.useState(null);
  const styles = useStyles();
  React.useEffect(() => {
    let isCancelled = false;
    const fetchData = async () => {
      setData(undefined);
      const newData = await getPreviewData(text);
      if (!isCancelled) {
        setData(newData);
      }
    };
    fetchData();
    return () => {
      isCancelled = true;
    };
  }, [text]);
  const handlePress = () => (data === null || data === void 0 ? void 0 : data.link) && Linking.openURL(data.link);
  const renderImageNode = React.useCallback(image => {
    const imageUrl = image ? {
      uri: image
    } : require('../../../core/assets/images/previewLinkDefaultBackground.png');
    return /*#__PURE__*/React.createElement(Image, {
      accessibilityRole: "image",
      resizeMode: "cover",
      source: imageUrl,
      style: styles.image
    });
  }, [styles.image]);
  const renderTitleNode = title => {
    return /*#__PURE__*/React.createElement(Text, {
      numberOfLines: 1,
      style: styles.title
    }, title);
  };
  const renderShortUrl = url => {
    const matches = url.match(/^https?:\/\/([^/?#]+)(?:[/?#]|$)/i);
    const shortUrl = matches ? matches[1] : '';
    return /*#__PURE__*/React.createElement(Text, {
      numberOfLines: 1,
      style: styles.shortUrl
    }, shortUrl);
  };
  return /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(RenderTextWithMention, {
    textPost: text,
    mentionPositionArr: mentionPositionArr
  }), (data === null || data === void 0 ? void 0 : data.link) && /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handlePress,
    style: styles.metadataContainer
  }, renderImageNode(data.image), /*#__PURE__*/React.createElement(View, {
    style: styles.metadataTextContainer
  }, (data === null || data === void 0 ? void 0 : data.link) && renderShortUrl(data.link), (data === null || data === void 0 ? void 0 : data.title) && renderTitleNode(data.title))));
});
//# sourceMappingURL=LinkPreview.js.map