import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useLocalSearchParams, router } from 'expo-router';
import { useState, useCallback } from 'react';
import { useFocusEffect } from 'expo-router';
import { ArrowLeft, Edit2, Trash2, MapPin, Phone } from 'lucide-react-native';
import { getDatabase } from '@/lib/database';
import { dbToContact } from '@/lib/contactHelpers';
import { Contact } from '@/store/useContactStore';
import { EditContactSheet } from '@/components/contacts/EditContactSheet';

const statusColors: Record<string, string> = {
  'Active': '#4CAF7D',
  'Return Visit': '#2196F3',
  'Bible Study': '#9C27B0',
  'Not Interested': '#9CA3AF',
  'Do Not Call': '#C0392B',
};

export default function ContactDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [contact, setContact] = useState<Contact | null>(null);
  const [showEdit, setShowEdit] = useState(false);

  async function loadContact() {
    const db = await getDatabase();
    const row = await db.getFirstAsync<any>('SELECT * FROM contacts WHERE id = ?', [id]);
    if (row) setContact(dbToContact(row));
  }

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

  async function handleDelete() {
    Alert.alert('Delete Contact', `Are you sure you want to delete ${contact?.fullName}?`, [
      { text: 'Cancel', style: 'cancel' },
      {
        text: 'Delete', style: 'destructive',
        onPress: async () => {
          const db = await getDatabase();
          const now = Math.floor(Date.now() / 1000);
          await db.runAsync('UPDATE contacts SET deleted_at = ? WHERE id = ?', [now, id]);
          router.back();
        }
      }
    ]);
  }

  if (!contact) return <View className="flex-1 bg-secondary" />;

  const statusColor = statusColors[contact.status] ?? '#9CA3AF';

  return (
    <View className="flex-1 bg-secondary">
      {/* Header */}
      <View className="bg-primary pt-14 pb-6 px-4">
        <View className="flex-row items-center justify-between mb-4">
          <TouchableOpacity onPress={() => router.back()} className="bg-white/20 rounded-full p-2">
            <ArrowLeft size={20} color="white" />
          </TouchableOpacity>
          <View className="flex-row gap-2">
            <TouchableOpacity onPress={() => setShowEdit(true)} className="bg-white/20 rounded-full p-2">
              <Edit2 size={18} color="white" />
            </TouchableOpacity>
            <TouchableOpacity onPress={handleDelete} className="bg-white/20 rounded-full p-2">
              <Trash2 size={18} color="white" />
            </TouchableOpacity>
          </View>
        </View>
        <View className="items-center">
          <View className="w-20 h-20 rounded-full bg-white/20 items-center justify-center mb-3">
            <Text className="text-white text-3xl font-bold">
              {contact.fullName.split(' ').map((n) => n[0]).join('').substring(0, 2).toUpperCase()}
            </Text>
          </View>
          <Text className="text-white text-xl font-bold">{contact.fullName}</Text>
          <View className="mt-2 px-3 py-1 rounded-full" style={{ backgroundColor: statusColor + '33' }}>
            <Text style={{ color: 'white' }} className="text-sm font-medium">{contact.status}</Text>
          </View>
        </View>
      </View>

      <ScrollView className="flex-1 px-4 pt-4" contentContainerStyle={{ gap: 12, paddingBottom: 40 }}>
        {/* Info Card */}
        <View className="bg-white rounded-2xl p-4">
          <Text className="text-charcoal font-semibold mb-3">Information</Text>
          <Row label="Category" value={contact.category} />
          {contact.address && <Row label="Address" value={contact.address} icon={<MapPin size={14} color="#9CA3AF" />} />}
          {contact.territoryCode && <Row label="Territory" value={contact.territoryCode} />}
        </View>

        {contact.notes && (
          <View className="bg-white rounded-2xl p-4">
            <Text className="text-charcoal font-semibold mb-2">Notes</Text>
            <Text className="text-gray-600">{contact.notes}</Text>
          </View>
        )}
      </ScrollView>

      <EditContactSheet contact={contact} visible={showEdit} onClose={() => setShowEdit(false)} onSaved={() => { setShowEdit(false); loadContact(); }} />
    </View>
  );
}

function Row({ label, value, icon }: { label: string; value: string; icon?: React.ReactNode }) {
  return (
    <View className="flex-row justify-between items-start py-2 border-b border-gray-50">
      <Text className="text-gray-500 text-sm">{label}</Text>
      <View className="flex-row items-center gap-1 flex-1 justify-end">
        {icon}
        <Text className="text-charcoal text-sm font-medium text-right flex-1" numberOfLines={2}>{value}</Text>
      </View>
    </View>
  );
}
