import React from 'react';
import { StyleSheet, TouchableOpacity, Linking } from 'react-native';
import { useRouter } from 'expo-router';
import { FeedItem } from '@/types/feed';
import { ThemedText } from './themed-text';
import { ThemedView } from './themed-view';
import { Colors, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

const EXTRACT_HTML_TEXT = (html: string): string => html.replace(/<[^>]*>/g, '');
const EXCERPT_LENGTH = 200;

interface FeedItemCardProps {
  item: FeedItem;
  onPress?: (item: FeedItem) => void;
  onLongPress?: (item: FeedItem) => void;
}

export function FeedItemCard({ item, onPress, onLongPress }: FeedItemCardProps) {
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];
  const router = useRouter();

  const handlePress = () => {
    if (onPress) {
      onPress(item);
    } else if (item.id) {
      router.push(`/article/${item.id}` as any);
    } else if (item.link) {
      Linking.openURL(item.link);
    }
  };

  const handleLongPress = () => {
    if (onLongPress) {
      onLongPress(item);
    }
  };

  const formatDate = (date?: Date) => {
    if (!date) return '';
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (days === 0) {
      const hours = Math.floor(diff / (1000 * 60 * 60));
      return hours === 0 ? 'Just now' : `${hours}h ago`;
    } else if (days === 1) {
      return 'Yesterday';
    } else if (days < 7) {
      return `${days}d ago`;
    } else {
      return date.toLocaleDateString();
    }
  };

  const excerpt = React.useMemo(() => {
    if (item.content) {
      const htmlContent = EXTRACT_HTML_TEXT(item.content);
      return htmlContent.length > EXCERPT_LENGTH ? htmlContent.substring(0, EXCERPT_LENGTH) + '...' : htmlContent;
    }
    if (item.description) {
      const htmlDesc = EXTRACT_HTML_TEXT(item.description);
      return htmlDesc.length > EXCERPT_LENGTH ? htmlDesc.substring(0, EXCERPT_LENGTH) + '...' : htmlDesc;
    }
    return '';
  }, [item.content, item.description]);

  const cardContent = (
    <TouchableOpacity
      style={[styles.container, { backgroundColor: colors.background }]}
      onPress={handlePress}
      onLongPress={handleLongPress}
      activeOpacity={0.7}
    >
      <ThemedView style={styles.content}>
        {item.subscriptionTitle && (
          <ThemedText type="small" style={styles.feedTitle} numberOfLines={1}>
            {item.subscriptionTitle}
          </ThemedText>
        )}
        
        <ThemedText type="smallBold" style={styles.title} numberOfLines={2}>
          {item.title}
        </ThemedText>
        
        {excerpt && (
          <ThemedText type="small" style={styles.excerpt} numberOfLines={3}>
            {excerpt}
          </ThemedText>
        )}
        
        <ThemedView style={styles.metaRow}>
          {item.author && (
            <ThemedText type="small" style={styles.author} numberOfLines={1}>
              {item.author}
            </ThemedText>
          )}
          {item.published && (
            <ThemedText type="small" style={styles.date}>
              {formatDate(item.published)}
            </ThemedText>
          )}
        </ThemedView>
        
        {item.enclosure && item.enclosure.type.includes('audio') && (
          <ThemedView style={styles.audioBadge}>
            <ThemedText type="small" style={styles.audioBadgeText}>
              🎧 Audio
            </ThemedText>
          </ThemedView>
        )}
      </ThemedView>
    </TouchableOpacity>
  );

  if (item.id) {
 return (
    <TouchableOpacity
      style={[styles.container, { backgroundColor: colors.background }]}
      onPress={handlePress}
      onLongPress={handleLongPress}
      activeOpacity={0.7}
    >
      <ThemedView style={styles.content}>
        {item.subscriptionTitle && (
          <ThemedText type="small" style={styles.feedTitle} numberOfLines={1}>
            {item.subscriptionTitle}
          </ThemedText>
        )}
        
        <ThemedText type="smallBold" style={styles.title} numberOfLines={2}>
          {item.title}
        </ThemedText>
        
        {excerpt && (
          <ThemedText type="small" style={styles.excerpt} numberOfLines={3}>
            {excerpt}
          </ThemedText>
        )}
        
        <ThemedView style={styles.metaRow}>
          {item.author && (
            <ThemedText type="small" style={styles.author} numberOfLines={1}>
              {item.author}
            </ThemedText>
          )}
          {item.published && (
            <ThemedText type="small" style={styles.date}>
              {formatDate(item.published)}
            </ThemedText>
          )}
        </ThemedView>
        
        {item.enclosure && item.enclosure.type.includes('audio') && (
          <ThemedView style={styles.audioBadge}>
            <ThemedText type="small" style={styles.audioBadgeText}>
              🎧 Audio
            </ThemedText>
          </ThemedView>
        )}
      </ThemedView>
    </TouchableOpacity>
  );
}

  return cardContent;
}

const styles = StyleSheet.create({
  container: {
    borderRadius: Spacing.three,
    padding: Spacing.three,
    marginBottom: Spacing.two,
    borderWidth: 1,
    borderColor: '#e5e5ea',
  },
  content: {
    flex: 1,
  },
  feedTitle: {
    fontSize: 12,
    color: '#007AFF',
    marginBottom: Spacing.half,
    fontWeight: '500',
  },
  title: {
    fontSize: 16,
    marginBottom: Spacing.one,
  },
  excerpt: {
    fontSize: 14,
    color: '#8e8e93',
    marginBottom: Spacing.two,
    lineHeight: 20,
  },
  metaRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Spacing.two,
  },
  author: {
    color: '#8e8e93',
    fontSize: 12,
    flex: 1,
  },
  date: {
    color: '#8e8e93',
    fontSize: 12,
  },
  audioBadge: {
    alignSelf: 'flex-start',
    paddingHorizontal: Spacing.two,
    paddingVertical: Spacing.one,
    backgroundColor: '#007AFF20',
    borderRadius: Spacing.one,
    marginTop: Spacing.two,
  },
  audioBadgeText: {
    color: '#007AFF',
    fontSize: 11,
    fontWeight: '600',
  },
});
