import { View, Text, TouchableOpacity, Modal, FlatList, TextInput } from 'react-native';
import { useState, useEffect } from 'react';
import { ChevronDown, Plus, X, Search } from 'lucide-react-native';
import { getDatabase } from '@/lib/database';
import * as Crypto from 'expo-crypto';

interface Props {
  value: string;
  onChange: (topic: string) => void;
}

interface Topic { id: string; name: string; is_default: number; }

export function TopicSelector({ value, onChange }: Props) {
  const [show, setShow] = useState(false);
  const [topics, setTopics] = useState<Topic[]>([]);
  const [search, setSearch] = useState('');
  const [newTopic, setNewTopic] = useState('');

  async function loadTopics() {
    const db = await getDatabase();
    const rows = await db.getAllAsync<Topic>('SELECT * FROM topics ORDER BY is_default DESC, name ASC');
    setTopics(rows);
  }

  useEffect(() => { if (show) loadTopics(); }, [show]);

  async function addCustomTopic() {
    if (!newTopic.trim()) return;
    const db = await getDatabase();
    const id = Crypto.randomUUID();
    const now = Math.floor(Date.now() / 1000);
    await db.runAsync('INSERT OR IGNORE INTO topics (id, name, is_default, created_at) VALUES (?, ?, 0, ?)', [id, newTopic.trim(), now]);
    setNewTopic('');
    await loadTopics();
  }

  const filtered = topics.filter((t) => t.name.toLowerCase().includes(search.toLowerCase()));

  return (
    <View className="mb-4">
      <Text className="text-charcoal font-medium mb-1">Topic</Text>
      <TouchableOpacity
        onPress={() => setShow(true)}
        className="flex-row items-center border border-gray-200 rounded-xl px-4 py-3 bg-white"
        accessibilityRole="button"
        accessibilityLabel={value ? `Selected topic: ${value}` : 'Select topic'}
        accessibilityHint="Opens topic selector"
        style={{ minHeight: 48 }}
      >
        <Text className={`flex-1 ${value ? 'text-charcoal' : 'text-gray-400'}`}>{value || 'Select topic...'}</Text>
        <ChevronDown size={16} color="#9CA3AF" />
      </TouchableOpacity>

      <Modal visible={show} animationType="slide" presentationStyle="pageSheet">
        <View className="flex-1 bg-secondary">
          <View className="flex-row items-center justify-between px-4 py-4 border-b border-gray-200 bg-white">
            <TouchableOpacity
              onPress={() => setShow(false)}
              accessibilityRole="button"
              accessibilityLabel="Close topic selector"
              style={{ minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }}
            >
              <X size={22} color="#2C3E50" />
            </TouchableOpacity>
            <Text className="text-charcoal font-semibold text-lg">Select Topic</Text>
            <View style={{ width: 44 }} />
          </View>

          <View className="px-4 pt-3 pb-2">
            <View className="flex-row items-center bg-white border border-gray-200 rounded-xl px-3 py-2 mb-3">
              <Search size={16} color="#9CA3AF" />
              <TextInput className="flex-1 text-charcoal ml-2" placeholder="Search topics..." value={search} onChangeText={setSearch} />
            </View>
            <View className="flex-row gap-2">
              <TextInput
                className="flex-1 border border-gray-200 rounded-xl px-3 py-2 bg-white text-charcoal"
                placeholder="Add custom topic..."
                value={newTopic}
                onChangeText={setNewTopic}
                onSubmitEditing={addCustomTopic}
              />
              <TouchableOpacity
                onPress={addCustomTopic}
                className="bg-primary rounded-xl px-3 items-center justify-center"
                accessibilityRole="button"
                accessibilityLabel="Add custom topic"
                style={{ minWidth: 44, minHeight: 44 }}
              >
                <Plus size={18} color="white" />
              </TouchableOpacity>
            </View>
          </View>

          <FlatList
            data={filtered}
            keyExtractor={(item) => item.id}
            contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 40, gap: 8 }}
            renderItem={({ item }) => (
              <TouchableOpacity
                onPress={() => { onChange(item.name); setShow(false); }}
                className={`bg-white rounded-xl px-4 py-3 flex-row items-center justify-between ${value === item.name ? 'border-2 border-primary' : 'border border-gray-100'}`}
                accessibilityRole="button"
                accessibilityLabel={item.name}
                accessibilityState={{ selected: value === item.name }}
                style={{ minHeight: 48 }}
              >
                <Text className="text-charcoal">{item.name}</Text>
                {item.is_default === 1 && <Text className="text-xs text-gray-400">Default</Text>}
              </TouchableOpacity>
            )}
          />
        </View>
      </Modal>
    </View>
  );
}
