// app/(tabs)/contacts.tsx
import { View, Text, FlatList, TouchableOpacity, TextInput } from 'react-native';
import { useState, useCallback } from 'react';
import { useFocusEffect } from 'expo-router';
import { Plus, Search, X } from 'lucide-react-native';
import { useContactStore, Contact } from '@/store/useContactStore';
import { getDatabase } from '@/lib/database';
import { ContactCard } from '@/components/contacts/ContactCard';
import { AddContactSheet } from '@/components/contacts/AddContactSheet';
import { dbToContact } from '@/lib/contactHelpers';

export default function ContactsScreen() {
  const { contacts, setContacts } = useContactStore();
  const [search, setSearch] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('All');
  const [showAdd, setShowAdd] = useState(false);

  const statusOptions = ['All', 'Active', 'Return Visit', 'Bible Study', 'Not Interested', 'Do Not Call'];

  async function loadContacts() {
    const db = await getDatabase();
    const rows = await db.getAllAsync<any>(
      'SELECT * FROM contacts WHERE deleted_at IS NULL ORDER BY full_name ASC'
    );
    setContacts(rows.map(dbToContact));
  }

  useFocusEffect(useCallback(() => { loadContacts(); }, []));

  const filtered = contacts.filter((c) => {
    const matchSearch = c.fullName.toLowerCase().includes(search.toLowerCase()) ||
      (c.address?.toLowerCase().includes(search.toLowerCase()) ?? false);
    const matchStatus = statusFilter === 'All' || c.status === statusFilter;
    return matchSearch && matchStatus;
  });

  return (
    <View className="flex-1 bg-secondary">
      {/* Header */}
      <View className="bg-primary pt-14 pb-4 px-4">
        <View className="flex-row justify-between items-center mb-3">
          <Text className="text-white text-2xl font-bold">Contacts</Text>
          <TouchableOpacity onPress={() => setShowAdd(true)} className="bg-white/20 rounded-full p-2">
            <Plus size={22} color="white" />
          </TouchableOpacity>
        </View>
        {/* Search */}
        <View className="flex-row items-center bg-white/20 rounded-xl px-3 py-2">
          <Search size={16} color="rgba(255,255,255,0.7)" />
          <TextInput
            className="flex-1 text-white ml-2"
            placeholder="Search contacts..."
            placeholderTextColor="rgba(255,255,255,0.6)"
            value={search}
            onChangeText={setSearch}
          />
          {search ? <TouchableOpacity onPress={() => setSearch('')}><X size={16} color="rgba(255,255,255,0.7)" /></TouchableOpacity> : null}
        </View>
      </View>

      {/* Status Filter */}
      <View className="py-2">
        <FlatList
          horizontal
          showsHorizontalScrollIndicator={false}
          contentContainerStyle={{ paddingHorizontal: 12, gap: 8 }}
          data={statusOptions}
          keyExtractor={(item) => item}
          renderItem={({ item }) => (
            <TouchableOpacity
              onPress={() => setStatusFilter(item)}
              className={`px-3 py-1.5 rounded-full border ${statusFilter === item ? 'bg-primary border-primary' : 'bg-white border-gray-200'}`}
            >
              <Text className={`text-sm font-medium ${statusFilter === item ? 'text-white' : 'text-charcoal'}`}>{item}</Text>
            </TouchableOpacity>
          )}
        />
      </View>

      {/* List */}
      <FlatList
        data={filtered}
        keyExtractor={(item) => item.id}
        contentContainerStyle={{ paddingHorizontal: 16, paddingBottom: 100, paddingTop: 4, gap: 8 }}
        renderItem={({ item }) => <ContactCard contact={item} onRefresh={loadContacts} />}
        ListEmptyComponent={() => (
          <View className="flex-1 items-center justify-center py-20">
            <Text className="text-gray-400 text-lg">
              {search ? 'No contacts found' : 'No contacts yet'}
            </Text>
            {!search && <Text className="text-gray-400 mt-1">Tap + to add your first contact</Text>}
          </View>
        )}
      />

      <AddContactSheet visible={showAdd} onClose={() => setShowAdd(false)} onSaved={() => { setShowAdd(false); loadContacts(); }} />
    </View>
  );
}
