import React from 'react';
import { FlatList, StyleSheet, View, Platform } from 'react-native';
import { RefreshControl } from 'react-native';
import { Animated, Easing } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useFeedList } from '@/hooks/use-feed-list';
import { FeedItemCard } from '@/components/feed-item-card';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { Colors, MaxContentWidth, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

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

export default function HomeScreen() {
  const { feedItems, loading, hasMore, loadMore, refreshFeed, isRefreshing, error } = useFeedList();
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];

  const fadeInAnim = React.useRef(new Animated.Value(0)).current;

  React.useEffect(() => {
    const anim = Animated.timing(fadeInAnim, {
      toValue: 1,
      duration: 300,
      easing: Easing.ease,
      useNativeDriver: true,
    });
    anim.start();
    return () => anim.stop();
  }, []);

  const renderFeedItem = React.useCallback(({ item, index }: { item: any; index: number }) => {
    const itemFadeIn = React.useMemo(() => new Animated.Value(0), []);
    
    React.useEffect(() => {
      const anim = Animated.timing(itemFadeIn, {
        toValue: 1,
        duration: 200,
        delay: Math.min(index * ANIMATION_DELAY_MULTIPLIER, MAX_ANIMATION_DELAY),
        easing: Easing.ease,
        useNativeDriver: true,
      });
      const timeout = setTimeout(() => anim.start(), 100);
      return () => {
        clearTimeout(timeout);
        anim.stop();
      };
    }, [itemFadeIn, index]);

    return (
      <Animated.View style={[styles.itemContainer, { opacity: itemFadeIn, transform: [{ translateY: itemFadeIn.interpolate({ inputRange: [0, 1], outputRange: [10, 0] }) }] }]}>
        <FeedItemCard item={item} />
      </Animated.View>
    );
  }, []);

  const renderHeader = () => (
    <ThemedView style={styles.header}>
      <ThemedText type="title" style={styles.headerTitle}>Today</ThemedText>
    </ThemedView>
  );

  const renderFooter = () => {
    if (!loading) return null;
    return (
      <ThemedView style={styles.footer}>
        <ThemedText type="small">Loading more...</ThemedText>
      </ThemedView>
    );
  };

  const renderEmpty = () => (
    <ThemedView style={styles.emptyContainer}>
      {error ? (
        <>
          <ThemedText type="title">Error Loading Feed</ThemedText>
          <ThemedText type="default" style={styles.emptySubtitle}>
            {error}
          </ThemedText>
          <ThemedText type="small" style={styles.retryHint}>
            Pull down to retry
          </ThemedText>
        </>
      ) : (
        <>
          <ThemedText type="title">No articles yet</ThemedText>
          <ThemedText type="default" style={styles.emptySubtitle}>
            Add a feed to start reading
          </ThemedText>
        </>
      )}
    </ThemedView>
  );

  return (
    <ThemedView style={styles.container}>
      <SafeAreaView style={styles.safeArea} edges={['top']}>
        {renderHeader()}
        
        <Animated.View style={{ opacity: fadeInAnim }}>
          {feedItems.length === 0 ? (
            renderEmpty()
          ) : (
            <FlatList
              data={feedItems}
              keyExtractor={(item) => item.id}
              renderItem={renderFeedItem}
              onEndReached={loadMore}
              onEndReachedThreshold={0.5}
              ListFooterComponent={renderFooter}
              refreshControl={
                <RefreshControl
                  refreshing={isRefreshing}
                  onRefresh={refreshFeed}
                  colors={[colors.text]}
                />
              }
              contentContainerStyle={styles.listContent}
              showsVerticalScrollIndicator={false}
            />
          )}
        </Animated.View>
      </SafeAreaView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.light.background,
  },
  safeArea: {
    flex: 1,
  },
  header: {
    paddingHorizontal: Spacing.four,
    paddingVertical: Spacing.three,
    maxWidth: MaxContentWidth,
  },
  headerTitle: {
    fontSize: 32,
    fontWeight: '700',
  },
  listContent: {
    paddingHorizontal: Spacing.four,
    paddingBottom: Spacing.six,
  },
  itemContainer: {
    maxWidth: MaxContentWidth,
  },
  footer: {
    paddingVertical: Spacing.four,
    alignItems: 'center',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: Spacing.four,
    gap: Spacing.two,
  },
  emptySubtitle: {
    textAlign: 'center',
    color: '#8e8e93',
  },
  retryHint: {
    marginTop: Spacing.three,
    color: '#007AFF',
    fontSize: 12,
  },
});
