import React, { useEffect, useState } from 'react';
import { StyleSheet, ScrollView, KeyboardAvoidingView, Platform, TouchableOpacity } from 'react-native';
import { SearchInput } from '@/components/search-input';
import { SearchSort } from '@/components/search-sort';
import { SearchResults } from '@/components/search-results';
import { SearchFilters } from '@/components/search-filters';
import { FilterOptions } from '@/components/filter-options';
import { combinedSearch } from '@/services/search-service';
import { useSearchStore } from '@/stores/search-store';
import { getAllSubscriptions } from '@/services/database';
import { SearchResult, SearchSortOption, SearchFilters as SearchFiltersType } from '@/types/feed';
import { ThemedText } from '@/components/themed-text';
import { ThemedView } from '@/components/themed-view';
import { Colors, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

export default function SearchScreen() {
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];
  
  const { query, setSort, setPage, setLoading, setError, sort, page, pageSize, loadHistory, loading, filters, setFilters } = useSearchStore();
  
  const [articles, setArticles] = useState<SearchResult[]>([]);
  const [feeds, setFeeds] = useState<SearchResult[]>([]);
  const [hasMore, setHasMore] = useState(false);
  const [isInitialLoad, setIsInitialLoad] = useState(true);
  const [filterModalVisible, setFilterModalVisible] = useState(false);
  const [availableFeeds, setAvailableFeeds] = useState<Array<{ id: string; title: string }>>([]);

  // Load search history and available feeds on mount
  useEffect(() => {
    loadHistory();
    
    const loadAvailableFeeds = async () => {
      try {
        const subscriptions = await getAllSubscriptions();
        setAvailableFeeds(subscriptions.map(s => ({ id: s.id, title: s.title })));
      } catch (error) {
        console.error('Failed to load available feeds:', error);
      }
    };
    
    loadAvailableFeeds();
  }, []);

  // Perform search when query, sort, filters, or page changes
  useEffect(() => {
    const performSearch = async () => {
      if (!query || query.trim().length === 0) {
        setArticles([]);
        setFeeds([]);
        setHasMore(false);
        return;
      }

      if (isInitialLoad) {
        setLoading(true);
      }

      try {
        const results = await combinedSearch(query, {
          filters,
          sort,
          page,
          pageSize,
        });

        if (page === 1) {
          setArticles(results.articles);
          setFeeds(results.feeds);
        } else {
          setArticles(prev => [...prev, ...results.articles]);
        }

        setHasMore(results.articles.length >= pageSize);
        setError(null);
      } catch (error) {
        setError(error instanceof Error ? error.message : 'Search failed');
        console.error('Search error:', error);
      } finally {
        setLoading(false);
        setIsInitialLoad(false);
      }
    };

    const timer = setTimeout(performSearch, 300);
    return () => clearTimeout(timer);
  }, [query, sort, filters, page, pageSize]);

  const handleSortChange = (newSort: SearchSortOption) => {
    setSort(newSort);
    setPage(1);
  };

  const handleFilterChange = (newFilters: Partial<SearchFiltersType>) => {
    setFilters(newFilters);
    setPage(1);
  };

  const handleClearAllFilters = () => {
    setFilters({});
    setPage(1);
  };

  const handleApplyFilters = (newFilters: SearchFiltersType) => {
    setFilters(newFilters);
    setPage(1);
  };

  const handleLoadMore = () => {
    if (!loading && hasMore) {
      setPage(page + 1);
    }
  };

  const handleResultPress = (result: SearchResult) => {
    console.log('Result pressed:', result);
  };

  return (
    <KeyboardAvoidingView
      style={styles.container}
      behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
      keyboardVerticalOffset={0}
    >
      <ScrollView
        style={styles.scrollView}
        keyboardShouldPersistTaps="handled"
        scrollEnabled={false}
      >
        <SearchInput autoFocus />
        <ThemedView style={styles.filtersRow}>
          <SearchSort sort={sort} onSortChange={handleSortChange} />
          <TouchableOpacity
            style={styles.filterButton}
            onPress={() => setFilterModalVisible(true)}
          >
            <ThemedText style={styles.filterButtonText}>🔍 Filters</ThemedText>
          </TouchableOpacity>
        </ThemedView>
        <SearchFilters
          filters={filters}
          onFilterChange={handleFilterChange}
          onClearAll={handleClearAllFilters}
          availableFeeds={availableFeeds}
        />
      </ScrollView>
      
      <ScrollView
        style={styles.resultsContainer}
        keyboardShouldPersistTaps="handled"
      >
        <SearchResults
          articles={articles}
          feeds={feeds}
          loading={loading}
          onLoadMore={handleLoadMore}
          onResultPress={handleResultPress}
          hasMore={hasMore}
        />
      </ScrollView>

      <FilterOptions
        visible={filterModalVisible}
        onClose={() => setFilterModalVisible(false)}
        currentFilters={filters}
        onApplyFilters={handleApplyFilters}
        availableFeeds={availableFeeds}
      />
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollView: {
    zIndex: 10,
  },
  filtersRow: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  filterButton: {
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    borderRadius: Spacing.two,
    backgroundColor: '#e5e5ea',
    marginLeft: Spacing.two,
  },
  filterButtonText: {
    fontSize: 14,
    color: '#8e8e93',
  },
  resultsContainer: {
    flex: 1,
  },
});
