import React, { useRef, useEffect } from 'react';
import { StyleSheet, TouchableOpacity, TextInput, ViewStyle, TextStyle } from 'react-native';
import { useSearchStore } from '@/stores/search-store';
import { ThemedText } from './themed-text';
import { ThemedView } from './themed-view';
import { Colors, Spacing } from '@/constants/theme';
import { useColorScheme } from 'react-native';

interface SearchInputProps {
  onSearch?: (query: string) => void;
  style?: ViewStyle;
  inputStyle?: TextStyle;
  placeholder?: string;
  autoFocus?: boolean;
}

export function SearchInput({ 
  onSearch, 
  style, 
  inputStyle, 
  placeholder = 'Search articles and feeds...',
  autoFocus = false,
}: SearchInputProps) {
  const scheme = useColorScheme();
  const colors = Colors[scheme === 'unspecified' ? 'light' : scheme];
  
  const { query, setQuery, clearSearch, searchHistory } = useSearchStore();
  const inputRef = useRef<TextInput>(null);
  
  // Debounced search handler
  useEffect(() => {
    if (!onSearch) return;
    
    const timer = setTimeout(() => {
      onSearch(query);
    }, 300);
    
    return () => clearTimeout(timer);
  }, [query, onSearch]);

  const handleClear = () => {
    setQuery('');
    inputRef.current?.focus();
  };

  const handleClearSearch = () => {
    clearSearch();
    inputRef.current?.focus();
  };

  return (
    <ThemedView style={[styles.container, style]}>
      <ThemedView style={styles.inputContainer}>
        <ThemedText style={styles.searchIcon}>🔍</ThemedText>
        <TextInput
          ref={inputRef}
          value={query}
          onChangeText={setQuery}
          placeholder={placeholder}
          placeholderTextColor={colors.textSecondary}
          style={[styles.input, inputStyle]}
          autoFocus={autoFocus}
          returnKeyType="search"
          keyboardType="default"
          autoCapitalize="none"
          autoCorrect={false}
          clearButtonMode="while-editing"
          selectionColor={colors.text}
        />
        {query ? (
          <TouchableOpacity
            onPress={handleClear}
            style={[styles.clearButton, { backgroundColor: colors.backgroundElement }]}
          >
            <ThemedText style={styles.clearIcon}>✕</ThemedText>
          </TouchableOpacity>
        ) : null}
      </ThemedView>
      
      {query && (
        <TouchableOpacity
          onPress={handleClearSearch}
          style={styles.clearSearchButton}
        >
          <ThemedText type="small" style={styles.clearSearchText}>
            Clear search
          </ThemedText>
        </TouchableOpacity>
      )}
      
      {searchHistory.length > 0 && !query && (
        <ThemedView style={styles.historyContainer}>
          <ThemedText type="small" style={styles.historyLabel}>
            Recent searches:
          </ThemedText>
          <ThemedView style={styles.historyList}>
            {searchHistory.map((item) => (
              <TouchableOpacity
                key={item.id}
                style={styles.historyItem}
                onPress={() => {
                  setQuery(item.query);
                  onSearch?.(item.query);
                }}
              >
                <ThemedText type="small" style={styles.historyText}>
                  {item.query}
                </ThemedText>
              </TouchableOpacity>
            ))}
          </ThemedView>
        </ThemedView>
      )}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    paddingHorizontal: Spacing.three,
    paddingBottom: Spacing.two,
  },
  inputContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f6f6f6',
    borderRadius: Spacing.three,
    paddingHorizontal: Spacing.three,
    height: 44,
  },
  searchIcon: {
    fontSize: 18,
    marginRight: Spacing.two,
  },
  input: {
    flex: 1,
    fontSize: 16,
    height: '100%',
  },
  clearButton: {
    width: 24,
    height: 24,
    borderRadius: 12,
    justifyContent: 'center',
    alignItems: 'center',
  },
  clearIcon: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  clearSearchButton: {
    alignItems: 'center',
    paddingVertical: Spacing.two,
  },
  clearSearchText: {
    color: '#007AFF',
  },
  historyContainer: {
    marginTop: Spacing.two,
  },
  historyLabel: {
    fontSize: 12,
    color: '#8e8e93',
    marginBottom: Spacing.two,
  },
  historyList: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    gap: Spacing.two,
  },
  historyItem: {
    paddingHorizontal: Spacing.three,
    paddingVertical: Spacing.two,
    backgroundColor: '#e5e5ea',
    borderRadius: Spacing.two,
  },
  historyText: {
    fontSize: 14,
  },
});
