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, ChevronRight } from 'lucide-react-native'; import { getDatabase } from '@/lib/database'; import { Territory, dbToTerritory } from '@/lib/territoryHelpers'; import { Contact } from '@/store/useContactStore'; import { dbToContact } from '@/lib/contactHelpers'; import { EditTerritorySheet } from '@/components/territories/EditTerritorySheet'; export default function TerritoryDetailScreen() { const { id } = useLocalSearchParams<{ id: string }>(); const [territory, setTerritory] = useState(null); const [contacts, setContacts] = useState([]); const [showEdit, setShowEdit] = useState(false); async function loadData() { const db = await getDatabase(); const row = await db.getFirstAsync('SELECT * FROM territories WHERE id = ?', [id]); if (row) { const t = dbToTerritory(row); setTerritory(t); const contactRows = await db.getAllAsync( 'SELECT * FROM contacts WHERE territory_code = ? AND deleted_at IS NULL ORDER BY full_name ASC', [t.territoryCode] ); setContacts(contactRows.map(dbToContact)); } } useFocusEffect(useCallback(() => { loadData(); }, [id])); async function handleDelete() { Alert.alert('Delete Territory', `Delete territory ${territory?.territoryCode}? Contacts will keep their territory code but it won't link to a territory record.`, [ { text: 'Cancel', style: 'cancel' }, { text: 'Delete', style: 'destructive', onPress: async () => { const db = await getDatabase(); await db.runAsync('DELETE FROM territories WHERE id = ?', [id]); router.back(); }} ]); } if (!territory) return ; return ( router.back()} className="bg-white/20 rounded-full p-2"> setShowEdit(true)} className="bg-white/20 rounded-full p-2"> {territory.territoryCode} {territory.territoryCode} {territory.barangay && {territory.barangay}{territory.municipality ? `, ${territory.municipality}` : ''}} Details {territory.municipality && } {territory.barangay && } {territory.area && } {territory.block && } Contacts in this territory ({contacts.length}) {contacts.length === 0 ? ( No contacts assigned to this territory ) : ( contacts.map((c) => ( router.push({ pathname: '/contact/[id]', params: { id: c.id } })} className="flex-row items-center py-2 border-b border-gray-50" > {c.fullName} {c.status} )) )} setShowEdit(false)} onSaved={() => { setShowEdit(false); loadData(); }} /> ); } function InfoRow({ label, value }: { label: string; value: string }) { return ( {label} {value} ); }