import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native';
import { useState, useEffect } from 'react';
import { X } from 'lucide-react-native';
import { Input } from '@/components/ui/Input';
import { Button } from '@/components/ui/Button';
import { getDatabase } from '@/lib/database';
import { Contact } from '@/store/useContactStore';

const STATUS_OPTIONS = ['Active', 'Return Visit', 'Bible Study', 'Not Interested', 'Do Not Call'];
const CATEGORY_OPTIONS = ['Adult', 'Teenager', 'Kid'];

interface Props {
  contact: Contact;
  visible: boolean;
  onClose: () => void;
  onSaved: () => void;
}

export function EditContactSheet({ contact, visible, onClose, onSaved }: Props) {
  const [fullName, setFullName] = useState(contact.fullName);
  const [address, setAddress] = useState(contact.address ?? '');
  const [status, setStatus] = useState(contact.status);
  const [category, setCategory] = useState(contact.category);
  const [notes, setNotes] = useState(contact.notes ?? '');
  const [territoryCode, setTerritoryCode] = useState(contact.territoryCode ?? '');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setFullName(contact.fullName);
    setAddress(contact.address ?? '');
    setStatus(contact.status);
    setCategory(contact.category);
    setNotes(contact.notes ?? '');
    setTerritoryCode(contact.territoryCode ?? '');
  }, [contact]);

  async function handleSave() {
    if (!fullName.trim()) return;
    setLoading(true);
    try {
      const db = await getDatabase();
      const now = Math.floor(Date.now() / 1000);
      await db.runAsync(
        'UPDATE contacts SET full_name=?, address=?, status=?, category=?, notes=?, territory_code=?, updated_at=? WHERE id=?',
        [fullName.trim(), address.trim() || null, status, category, notes.trim() || null, territoryCode.trim().toUpperCase() || null, now, contact.id]
      );
      onSaved();
    } finally {
      setLoading(false);
    }
  }

  return (
    <Modal visible={visible} animationType="slide" presentationStyle="pageSheet" onRequestClose={onClose}>
      <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : 'height'} className="flex-1">
        <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={onClose}><X size={22} color="#2C3E50" /></TouchableOpacity>
            <Text className="text-charcoal font-semibold text-lg">Edit Contact</Text>
            <View style={{ width: 22 }} />
          </View>
          <ScrollView className="flex-1 px-4 pt-4" keyboardShouldPersistTaps="handled">
            <Input label="Full Name *" value={fullName} onChangeText={setFullName} />
            <Input label="Address" value={address} onChangeText={setAddress} />
            <Text className="text-charcoal font-medium mb-2">Status</Text>
            <View className="flex-row flex-wrap gap-2 mb-4">
              {STATUS_OPTIONS.map((s) => (
                <TouchableOpacity key={s} onPress={() => setStatus(s as any)} className={`px-3 py-1.5 rounded-full border ${status === s ? 'bg-primary border-primary' : 'bg-white border-gray-200'}`}>
                  <Text className={`text-sm ${status === s ? 'text-white' : 'text-charcoal'}`}>{s}</Text>
                </TouchableOpacity>
              ))}
            </View>
            <Text className="text-charcoal font-medium mb-2">Category</Text>
            <View className="flex-row gap-2 mb-4">
              {CATEGORY_OPTIONS.map((c) => (
                <TouchableOpacity key={c} onPress={() => setCategory(c as any)} className={`px-3 py-1.5 rounded-full border ${category === c ? 'bg-primary border-primary' : 'bg-white border-gray-200'}`}>
                  <Text className={`text-sm ${category === c ? 'text-white' : 'text-charcoal'}`}>{c}</Text>
                </TouchableOpacity>
              ))}
            </View>
            {/* Territory Code */}
            <Input label="Territory Code" placeholder="e.g. T-01" value={territoryCode} onChangeText={setTerritoryCode} autoCapitalize="characters" />
            <Input label="Notes" value={notes} onChangeText={setNotes} multiline numberOfLines={3} />
            <View className="h-8" />
          </ScrollView>
          <View className="px-4 py-4 border-t border-gray-200 bg-white">
            <Button label="Save Changes" onPress={handleSave} loading={loading} />
          </View>
        </View>
      </KeyboardAvoidingView>
    </Modal>
  );
}
