import React, {memo, useCallback, useState} from 'react';
import {
  View,
  TouchableOpacity,
  ViewStyle,
  LayoutChangeEvent,
} from 'react-native';
import AutoHeightImage from 'react-native-auto-height-image';
import DeleteButton from '@components/DeleteButton';
import Text from '@components/Text';
import {LinkPreview} from '@interfaces/linkPreview';
import {ImageUrl} from '@interfaces/generic';
import {Opacity} from '@shared/constants';

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

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

/**
 * @deprecated Use `_custom/LinkPreviewCard` instead
 */
function LinkPreviewCard({
  data,
  disabled,
  onClose,
  onPress,
  showCloseButton,
  style,
  showDescription = false,
}: LinkPreviewCardProps) {
  const [componentWidth, setComponentWidth] = useState<number>(0);
  const [isImageError, setIsImageError] = useState(false);
  const showBottomCard = data?.domainName || data?.title || data?.description;
  const showPreview = data && ((data.image && !isImageError) || showBottomCard);

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

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

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

  return showPreview ? (
    <TouchableOpacity
      activeOpacity={Opacity.FULL}
      disabled={disabled}
      onPress={handleLinkPress}
      style={[styles.container, style]}
      onLayout={handleLayout}>
      {showCloseButton && (
        <DeleteButton
          top={10}
          right={10}
          onPress={onClose}
          containerStyle={styles.deleteButton}
        />
      )}
      {data.image && (
        <AutoHeightImage
          source={{uri: data.image}}
          resizeMode="contain"
          width={componentWidth}
          maxHeight={componentWidth}
          onError={handleImageError}
        />
      )}
      {showBottomCard && (
        <View style={styles.bottomCard}>
          {data.url && (
            <Text style={styles.bottomCardText}>
              {getDomain(data.url)?.toUpperCase()}
            </Text>
          )}
          {data.title && (
            <Text
              numberOfLines={1}
              style={[styles.bottomCardText, styles.title]}>
              {data.title}
            </Text>
          )}
          {showDescription && data.description && (
            <Text
              numberOfLines={2}
              style={[styles.bottomCardText, styles.description]}>
              {data.description}
            </Text>
          )}
        </View>
      )}
    </TouchableOpacity>
  ) : null;
}

export default memo(LinkPreviewCard);
