import { View, Text, ScrollView, TouchableOpacity, Alert } from 'react-native';
import { useLocalSearchParams, router, useFocusEffect } from 'expo-router';
import { useState, useCallback } from 'react';
import { ArrowLeft, Edit2, Trash2, MapPin } 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';
import { LogVisitSheet } from '@/components/visits/LogVisitSheet';
import { Visit, dbToVisit, formatDate } from '@/lib/visitHelpers';

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 [visits, setVisits] = useState<Visit[]>([]);
  const [showEdit, setShowEdit] = useState(false);
  const [showLogVisit, setShowLogVisit] = useState(false);

  async function loadData() {
    const db = await getDatabase();
    const row = await db.getFirstAsync<any>('SELECT * FROM contacts WHERE id = ?', [id]);
    if (row) setContact(dbToContact(row));
    const visitRows = await db.getAllAsync<any>('SELECT * FROM visits WHERE contact_id = ? ORDER BY visit_date DESC', [id]);
    setVisits(visitRows.map(dbToVisit));
  }

  useFocusEffect(useCallback(() => { loadData(); }, [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();
          await db.runAsync('UPDATE contacts SET deleted_at = ? WHERE id = ?', [Math.floor(Date.now() / 1000), 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">
      <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 }}>
        <View className="bg-white rounded-2xl p-4">
          <Text className="text-charcoal font-semibold mb-3">Information</Text>
          <InfoRow label="Category" value={contact.category} />
          {contact.address && <InfoRow label="Address" value={contact.address} />}
          {contact.territoryCode && <InfoRow 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>
        )}

        <View className="bg-white rounded-2xl p-4">
          <View className="flex-row justify-between items-center mb-3">
            <Text className="text-charcoal font-semibold">Visit History ({visits.length})</Text>
            <TouchableOpacity onPress={() => setShowLogVisit(true)} className="bg-primary rounded-lg px-3 py-1.5">
              <Text className="text-white text-sm font-medium">+ Log Visit</Text>
            </TouchableOpacity>
          </View>
          {visits.length === 0 ? (
            <Text className="text-gray-400 text-sm">No visits recorded yet</Text>
          ) : (
            visits.map((v) => (
              <View key={v.id} className="border-l-2 border-primary pl-3 mb-3 last:mb-0">
                <Text className="text-charcoal font-medium text-sm">{formatDate(v.visitDate)}</Text>
                {v.topic && <Text className="text-gray-500 text-sm mt-0.5">📖 {v.topic}</Text>}
                {v.response && <Text className="text-gray-500 text-sm mt-0.5">💬 {v.response}</Text>}
                {v.remarks && <Text className="text-gray-400 text-xs mt-0.5">{v.remarks}</Text>}
                {v.nextVisitDate && <Text className="text-primary text-xs mt-0.5 font-medium">Next: {formatDate(v.nextVisitDate)}</Text>}
              </View>
            ))
          )}
        </View>
      </ScrollView>

      <EditContactSheet contact={contact} visible={showEdit} onClose={() => setShowEdit(false)} onSaved={() => { setShowEdit(false); loadData(); }} />
      <LogVisitSheet
        contactId={contact.id}
        contactName={contact.fullName}
        visible={showLogVisit}
        onClose={() => setShowLogVisit(false)}
        onSaved={() => { setShowLogVisit(false); loadData(); }}
      />
    </View>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  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>
      <Text className="text-charcoal text-sm font-medium text-right flex-1 ml-4" numberOfLines={2}>{value}</Text>
    </View>
  );
}
