import React, { useState } from 'react';
import { StyleSheet, FlatList, ViewToken, ActivityIndicator } from 'react-native';
import { SearchResult } from '@/types/feed';
import { ThemedText } from './themed-text';
import { ThemedView } from './themed-view';
import { ArticleCard } from './article-card';
import { Colors, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

interface SearchResultsProps {
  articles: SearchResult[];
  feeds: SearchResult[];
  loading: boolean;
  onLoadMore?: () => void;
  onResultPress?: (result: SearchResult) => void;
  hasMore?: boolean;
}

export function SearchResults({ 
  articles, 
  feeds, 
  loading,
  onLoadMore,
  onResultPress,
  hasMore = false,
}: SearchResultsProps) {
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];
  
  const [visibleArticles, setVisibleArticles] = useState<Set<string>>(new Set());
  const [visibleFeeds, setVisibleFeeds] = useState<Set<string>>(new Set());

  const keyExtractor = (item: SearchResult) => item.id;

  const onViewableItemsChangedArticles = ({ viewableItems }: { viewableItems: ViewToken[] }) => {
    const newVisible = new Set(visibleArticles);
    viewableItems.forEach(item => {
      if (item.isViewable) {
        newVisible.add(item.key);
      }
    });
    setVisibleArticles(newVisible);
  };

  const onViewableItemsChangedFeeds = ({ viewableItems }: { viewableItems: ViewToken[] }) => {
    const newVisible = new Set(visibleFeeds);
    viewableItems.forEach(item => {
      if (item.isViewable) {
        newVisible.add(item.key);
      }
    });
    setVisibleFeeds(newVisible);
  };

  const viewabilityConfig = {
    itemVisiblePercentThreshold: 50,
  };

  const renderArticle = ({ item }: { item: SearchResult }) => (
    <ArticleCard result={item} onPress={onResultPress} />
  );

  const renderFeed = ({ item }: { item: SearchResult }) => (
    <ArticleCard result={item} onPress={onResultPress} />
  );

  const renderFooter = () => {
    if (!loading || !hasMore) return null;
    return (
      <ThemedView style={styles.loadingContainer}>
        <ActivityIndicator size="small" color={colors.text} />
      </ThemedView>
    );
  };

  const renderEmptyState = () => {
    if (!loading && articles.length === 0 && feeds.length === 0) {
      return (
        <ThemedView style={styles.emptyContainer}>
          <ThemedText type="section" style={styles.emptyTitle}>
            No results found
          </ThemedText>
          <ThemedText type="small" style={styles.emptySubtitle}>
            Try different keywords or check your filters
          </ThemedText>
        </ThemedView>
      );
    }
    return null;
  };

  return (
    <ThemedView style={styles.container}>
      {feeds.length > 0 && (
        <ThemedView style={styles.section}>
          <ThemedText type="smallBold" style={styles.sectionHeader}>
            Feeds ({feeds.length})
          </ThemedText>
          <FlatList
            data={feeds}
            renderItem={renderFeed}
            keyExtractor={keyExtractor}
            horizontal
            showsHorizontalScrollIndicator={false}
            contentContainerStyle={styles.feedsList}
            onViewableItemsChanged={onViewableItemsChangedFeeds}
            viewabilityConfig={viewabilityConfig}
          />
        </ThemedView>
      )}
      
      <ThemedView style={styles.section}>
        {(articles.length > 0 || loading) && (
          <ThemedText type="smallBold" style={styles.sectionHeader}>
            Articles ({articles.length})
          </ThemedText>
        )}
        
        {renderEmptyState()}
        
        <FlatList
          data={articles}
          renderItem={renderArticle}
          keyExtractor={keyExtractor}
          onEndReached={onLoadMore}
          onEndReachedThreshold={0.5}
          ListFooterComponent={renderFooter}
          onViewableItemsChanged={onViewableItemsChangedArticles}
          viewabilityConfig={viewabilityConfig}
          contentContainerStyle={styles.articlesList}
        />
      </ThemedView>
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  section: {
    paddingHorizontal: Spacing.three,
    paddingBottom: Spacing.three,
  },
  sectionHeader: {
    fontSize: 14,
    marginBottom: Spacing.three,
    marginTop: Spacing.two,
  },
  feedsList: {
    paddingRight: Spacing.three,
  },
  articlesList: {
    paddingBottom: Spacing.four,
  },
  loadingContainer: {
    paddingVertical: Spacing.four,
    alignItems: 'center',
  },
  emptyContainer: {
    paddingVertical: Spacing.six * 2,
    alignItems: 'center',
  },
  emptyTitle: {
    textAlign: 'center',
    marginBottom: Spacing.two,
  },
  emptySubtitle: {
    textAlign: 'center',
    color: '#8e8e93',
  },
});
