import React, { useState, useRef, useEffect } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TextInput,
  Modal,
  FlatList,
  Pressable,
  Keyboard,
} from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import { SafeAreaView } from 'react-native-safe-area-context';

interface SearchableDropdownProps {
  label?: string;
  placeholder?: string;
  items: string[];
  selectedItems: string[];
  onSelectionChange: (items: string[]) => void;
  multiSelect?: boolean;
  groupedItems?: { [key: string]: string[] };
}

export const SearchableDropdown: React.FC<SearchableDropdownProps> = ({
  label,
  placeholder = 'Search...',
  items,
  selectedItems,
  onSelectionChange,
  multiSelect = true,
  groupedItems,
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const searchInputRef = useRef<TextInput>(null);

  useEffect(() => {
    if (isOpen && searchInputRef.current) {
      setTimeout(() => searchInputRef.current?.focus(), 100);
    }
  }, [isOpen]);

  const filteredItems = searchQuery
    ? items.filter(item => item.toLowerCase().includes(searchQuery.toLowerCase()))
    : items;

  const getGroupForItem = (item: string): string | null => {
    if (!groupedItems) return null;
    for (const [group, groupItems] of Object.entries(groupedItems)) {
      if (groupItems.includes(item)) return group;
    }
    return null;
  };

  const getGroupLabel = (group: string): string => {
    switch (group) {
      case 'thoroughbred': return 'Thoroughbred';
      case 'harness': return 'Harness';
      case 'greyhound': return 'Greyhound';
      default: return group;
    }
  };

  const getGroupColor = (group: string): string => {
    switch (group) {
      case 'thoroughbred': return '#3b82f6';
      case 'harness': return '#8b5cf6';
      case 'greyhound': return '#22c55e';
      default: return '#6b7280';
    }
  };

  const handleItemPress = (item: string) => {
    if (multiSelect) {
      if (selectedItems.includes(item)) {
        onSelectionChange(selectedItems.filter(i => i !== item));
      } else {
        onSelectionChange([...selectedItems, item]);
      }
    } else {
      onSelectionChange([item]);
      setIsOpen(false);
    }
  };

  const handleClearAll = () => {
    onSelectionChange([]);
  };

  const renderItem = ({ item }: { item: string }) => {
    const isSelected = selectedItems.includes(item);
    const group = getGroupForItem(item);
    
    return (
      <TouchableOpacity
        style={[styles.dropdownItem, isSelected && styles.dropdownItemSelected]}
        onPress={() => handleItemPress(item)}
        activeOpacity={0.7}
      >
        <View style={styles.itemContent}>
          <Text style={[styles.itemText, isSelected && styles.itemTextSelected]}>
            {item}
          </Text>
          {group && (
            <View style={[styles.groupBadge, { backgroundColor: getGroupColor(group) + '20' }]}>
              <Text style={[styles.groupBadgeText, { color: getGroupColor(group) }]}>
                {getGroupLabel(group)}
              </Text>
            </View>
          )}
        </View>
        {isSelected && (
          <Ionicons name="checkmark-circle" size={22} color="#111827" />
        )}
      </TouchableOpacity>
    );
  };

  const displayValue = selectedItems.length === 0
    ? 'All tracks'
    : selectedItems.length === 1
      ? selectedItems[0]
      : `${selectedItems.length} tracks selected`;

  return (
    <View style={styles.container}>
      {label && <Text style={styles.label}>{label}</Text>}
      
      <TouchableOpacity
        style={styles.selector}
        onPress={() => setIsOpen(true)}
        activeOpacity={0.7}
      >
        <Ionicons name="location-outline" size={20} color="#6b7280" />
        <Text style={[
          styles.selectorText,
          selectedItems.length === 0 && styles.selectorPlaceholder
        ]}>
          {displayValue}
        </Text>
        <Ionicons name="chevron-down" size={20} color="#6b7280" />
      </TouchableOpacity>

      <Modal
        visible={isOpen}
        animationType="slide"
        presentationStyle="pageSheet"
        onRequestClose={() => setIsOpen(false)}
      >
        <SafeAreaView style={styles.modalContainer} edges={['top']}>
          <View style={styles.modalHeader}>
            <TouchableOpacity
              style={styles.closeButton}
              onPress={() => {
                setIsOpen(false);
                setSearchQuery('');
              }}
            >
              <Ionicons name="close" size={24} color="#111827" />
            </TouchableOpacity>
            <Text style={styles.modalTitle}>Select Tracks</Text>
            {multiSelect && selectedItems.length > 0 && (
              <TouchableOpacity style={styles.clearButton} onPress={handleClearAll}>
                <Text style={styles.clearButtonText}>Clear</Text>
              </TouchableOpacity>
            )}
            {(!multiSelect || selectedItems.length === 0) && (
              <View style={styles.headerSpacer} />
            )}
          </View>

          <View style={styles.searchContainer}>
            <Ionicons name="search-outline" size={20} color="#9ca3af" />
            <TextInput
              ref={searchInputRef}
              style={styles.searchInput}
              placeholder={placeholder}
              placeholderTextColor="#9ca3af"
              value={searchQuery}
              onChangeText={setSearchQuery}
              autoCorrect={false}
              autoCapitalize="none"
            />
            {searchQuery !== '' && (
              <TouchableOpacity onPress={() => setSearchQuery('')}>
                <Ionicons name="close-circle" size={20} color="#9ca3af" />
              </TouchableOpacity>
            )}
          </View>

          {multiSelect && (
            <View style={styles.selectedInfo}>
              <Text style={styles.selectedInfoText}>
                {selectedItems.length === 0
                  ? 'No tracks selected (showing all)'
                  : `${selectedItems.length} track${selectedItems.length !== 1 ? 's' : ''} selected`}
              </Text>
            </View>
          )}

          <FlatList
            data={filteredItems}
            renderItem={renderItem}
            keyExtractor={item => item}
            style={styles.list}
            contentContainerStyle={styles.listContent}
            keyboardShouldPersistTaps="handled"
            ListEmptyComponent={
              <View style={styles.emptyState}>
                <Text style={styles.emptyStateText}>No tracks found</Text>
              </View>
            }
          />

          {multiSelect && (
            <View style={styles.modalFooter}>
              <TouchableOpacity
                style={styles.doneButton}
                onPress={() => {
                  setIsOpen(false);
                  setSearchQuery('');
                }}
              >
                <Text style={styles.doneButtonText}>Done</Text>
              </TouchableOpacity>
            </View>
          )}
        </SafeAreaView>
      </Modal>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    marginBottom: 16,
  },
  label: {
    fontSize: 14,
    fontWeight: '600',
    color: '#374151',
    marginBottom: 8,
  },
  selector: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 14,
    gap: 10,
    borderWidth: 1,
    borderColor: '#e5e7eb',
  },
  selectorText: {
    flex: 1,
    fontSize: 16,
    color: '#111827',
  },
  selectorPlaceholder: {
    color: '#9ca3af',
  },
  modalContainer: {
    flex: 1,
    backgroundColor: '#f9fafb',
  },
  modalHeader: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    paddingVertical: 12,
    borderBottomWidth: 1,
    borderBottomColor: '#e5e7eb',
    backgroundColor: '#fff',
  },
  closeButton: {
    width: 40,
    height: 40,
    alignItems: 'center',
    justifyContent: 'center',
  },
  modalTitle: {
    fontSize: 18,
    fontWeight: '700',
    color: '#111827',
  },
  clearButton: {
    paddingHorizontal: 12,
    paddingVertical: 8,
  },
  clearButtonText: {
    fontSize: 16,
    color: '#ef4444',
    fontWeight: '600',
  },
  headerSpacer: {
    width: 60,
  },
  searchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#fff',
    marginHorizontal: 16,
    marginTop: 16,
    marginBottom: 8,
    paddingHorizontal: 14,
    paddingVertical: 12,
    borderRadius: 12,
    gap: 10,
    borderWidth: 1,
    borderColor: '#e5e7eb',
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    color: '#111827',
  },
  selectedInfo: {
    paddingHorizontal: 20,
    paddingVertical: 8,
  },
  selectedInfoText: {
    fontSize: 13,
    color: '#6b7280',
  },
  list: {
    flex: 1,
  },
  listContent: {
    paddingHorizontal: 16,
    paddingBottom: 16,
  },
  dropdownItem: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    backgroundColor: '#fff',
    padding: 16,
    borderRadius: 12,
    marginBottom: 8,
    borderWidth: 1,
    borderColor: '#e5e7eb',
  },
  dropdownItemSelected: {
    backgroundColor: '#f3f4f6',
    borderColor: '#111827',
  },
  itemContent: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    gap: 10,
  },
  itemText: {
    fontSize: 16,
    color: '#111827',
  },
  itemTextSelected: {
    fontWeight: '600',
  },
  groupBadge: {
    paddingHorizontal: 8,
    paddingVertical: 3,
    borderRadius: 10,
  },
  groupBadgeText: {
    fontSize: 11,
    fontWeight: '600',
  },
  emptyState: {
    padding: 32,
    alignItems: 'center',
  },
  emptyStateText: {
    fontSize: 16,
    color: '#6b7280',
  },
  modalFooter: {
    padding: 16,
    backgroundColor: '#fff',
    borderTopWidth: 1,
    borderTopColor: '#e5e7eb',
  },
  doneButton: {
    backgroundColor: '#111827',
    borderRadius: 12,
    paddingVertical: 16,
    alignItems: 'center',
  },
  doneButtonText: {
    fontSize: 17,
    fontWeight: '700',
    color: '#fff',
  },
});
