import { View, Text, Modal, ScrollView, TouchableOpacity, KeyboardAvoidingView, Platform } from 'react-native'; import { useState } 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 { newTerritoryId } from '@/lib/territoryHelpers'; interface Props { visible: boolean; onClose: () => void; onSaved: () => void; } export function AddTerritorySheet({ visible, onClose, onSaved }: Props) { const [code, setCode] = useState(''); const [municipality, setMunicipality] = useState(''); const [barangay, setBarangay] = useState(''); const [area, setArea] = useState(''); const [block, setBlock] = useState(''); const [errors, setErrors] = useState>({}); const [loading, setLoading] = useState(false); function reset() { setCode(''); setMunicipality(''); setBarangay(''); setArea(''); setBlock(''); setErrors({}); } async function handleSave() { const errs: Record = {}; if (!code.trim()) errs.code = 'Territory code is required'; if (Object.keys(errs).length) { setErrors(errs); return; } setLoading(true); try { const db = await getDatabase(); const now = Math.floor(Date.now() / 1000); await db.runAsync( 'INSERT INTO territories (id, territory_code, municipality, barangay, area, block, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)', [newTerritoryId(), code.trim().toUpperCase(), municipality.trim() || null, barangay.trim() || null, area.trim() || null, block.trim() || null, now, now] ); reset(); onSaved(); } catch (e: any) { if (e?.message?.includes('UNIQUE')) setErrors({ code: 'Territory code already exists' }); } finally { setLoading(false); } } return ( { reset(); onClose(); }}> { reset(); onClose(); }}> New Territory { setCode(t); setErrors((e) => ({ ...e, code: '' })); }} error={errors.code} autoCapitalize="characters" />