import React, {memo, useCallback, useState} from 'react';
import {View, ViewStyle, LayoutChangeEvent} from 'react-native';
import AutoHeightImage from 'react-native-auto-height-image';
import {Pressable, Typography} from '@components/_core';
import {LinkPreview} from '@interfaces/linkPreview';
import {ImageUrl} from '@interfaces/generic';
import {useTheme} from '@shared/theme';
import {openUrlFromApp} from '@shared/utils';

import {getDomain} from './utils';
import {styles} from './styles';

export interface LinkPreviewCardProps {
  data?: LinkPreview & ImageUrl;
  disabled?: boolean;
  onPress?: (target: string) => void;
  style?: ViewStyle;
  showDescription?: boolean;
}

function LinkPreviewCard({
  data,
  disabled,
  onPress = openUrlFromApp,
  style,
  showDescription = false,
}: LinkPreviewCardProps) {
  const {theme, spacing} = useTheme();
  const [componentWidth, setComponentWidth] = useState(0);
  const [isImageError, setIsImageError] = useState(false);
  const showBottomText = data?.domainName || data?.title || data?.description;
  const showPreview = data && ((data.image && !isImageError) || showBottomText);

  const onLinkPress = useCallback(() => {
    onPress?.(data!.url);
  }, [onPress, data]);

  const onLayout = (event: LayoutChangeEvent) => {
    componentWidth === 0 && setComponentWidth(event.nativeEvent.layout.width);
  };

  const onImageError = () => setIsImageError(true);

  return showPreview ? (
    <Pressable
      disabled={disabled}
      onPress={onLinkPress}
      style={[
        styles.container,
        {borderColor: theme.border.neutral.default},
        style,
      ]}
      onLayout={onLayout}>
      {data.image && (
        <AutoHeightImage
          source={{uri: data.image}}
          resizeMode="contain"
          width={componentWidth - spacing.x8}
          maxHeight={componentWidth}
          onError={onImageError}
        />
      )}
      {showBottomText && (
        <View style={styles.bottomTextContainer}>
          {data.url && (
            <Typography variant="xxs" color={theme.neutralTextLighter}>
              {getDomain(data.url)?.toLowerCase()}
            </Typography>
          )}
          {data.title && (
            <Typography numberOfLines={1} variant="m" weight="semiBold">
              {data.title}
            </Typography>
          )}
          {showDescription && data.description && (
            <Typography numberOfLines={2} variant="xs">
              {data.description}
            </Typography>
          )}
        </View>
      )}
    </Pressable>
  ) : null;
}

export default memo(LinkPreviewCard);
