import { View, Text, ScrollView, TouchableOpacity } 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';
import { ConfirmDialog } from '@/components/ui/ConfirmDialog';
import { EmptyState } from '@/components/ui/EmptyState';
import { useToast } from '@/components/ui/Toast';

export default function TerritoryDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const [territory, setTerritory] = useState<Territory | null>(null);
  const [contacts, setContacts] = useState<Contact[]>([]);
  const [showEdit, setShowEdit] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const { showToast } = useToast();

  async function loadData() {
    const db = await getDatabase();
    const row = await db.getFirstAsync<any>('SELECT * FROM territories WHERE id = ?', [id]);
    if (row) {
      const t = dbToTerritory(row);
      setTerritory(t);
      const contactRows = await db.getAllAsync<any>(
        '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 handleDeleteConfirmed() {
    const db = await getDatabase();
    await db.runAsync('DELETE FROM territories WHERE id = ?', [id]);
    showToast(`Territory ${territory?.territoryCode} deleted`, 'success');
    router.back();
  }

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

  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"
            accessibilityRole="button"
            accessibilityLabel="Go back"
            style={{ minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }}
          >
            <ArrowLeft size={20} color="white" />
          </TouchableOpacity>
          <View className="flex-row gap-2">
            <TouchableOpacity
              onPress={() => setShowEdit(true)}
              className="bg-white/20 rounded-full p-2"
              accessibilityRole="button"
              accessibilityLabel="Edit territory"
              style={{ minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }}
            >
              <Edit2 size={18} color="white" />
            </TouchableOpacity>
            <TouchableOpacity
              onPress={() => setShowDeleteConfirm(true)}
              className="bg-white/20 rounded-full p-2"
              accessibilityRole="button"
              accessibilityLabel="Delete territory"
              style={{ minWidth: 44, minHeight: 44, alignItems: 'center', justifyContent: 'center' }}
            >
              <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-2xl font-bold">{territory.territoryCode}</Text>
          </View>
          <Text className="text-white text-xl font-bold">{territory.territoryCode}</Text>
          {territory.barangay && <Text className="text-white/70 text-sm mt-1">{territory.barangay}{territory.municipality ? `, ${territory.municipality}` : ''}</Text>}
        </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">Details</Text>
          {territory.municipality && <InfoRow label="Municipality" value={territory.municipality} />}
          {territory.barangay && <InfoRow label="Barangay" value={territory.barangay} />}
          {territory.area && <InfoRow label="Area" value={territory.area} />}
          {territory.block && <InfoRow label="Block" value={territory.block} />}
        </View>

        <View className="bg-white rounded-2xl p-4">
          <Text className="text-charcoal font-semibold mb-3">Contacts in this territory ({contacts.length})</Text>
          {contacts.length === 0 ? (
            <EmptyState
              icon="Users"
              title="No contacts here yet"
              message="Assign contacts to this territory to see them here."
            />
          ) : (
            contacts.map((c) => (
              <TouchableOpacity
                key={c.id}
                onPress={() => router.push({ pathname: '/contact/[id]', params: { id: c.id } })}
                className="flex-row items-center py-2 border-b border-gray-50"
                accessibilityRole="button"
                accessibilityLabel={`View contact ${c.fullName}`}
                style={{ minHeight: 44 }}
              >
                <Text className="flex-1 text-charcoal font-medium">{c.fullName}</Text>
                <Text className="text-gray-400 text-xs mr-2">{c.status}</Text>
                <ChevronRight size={14} color="#9CA3AF" />
              </TouchableOpacity>
            ))
          )}
        </View>
      </ScrollView>

      <EditTerritorySheet territory={territory} visible={showEdit} onClose={() => setShowEdit(false)} onSaved={() => { setShowEdit(false); loadData(); }} />

      <ConfirmDialog
        visible={showDeleteConfirm}
        title="Delete Territory"
        message={`Delete territory ${territory.territoryCode}? Contacts will keep their territory code but it won't link to a territory record.`}
        confirmText="Delete"
        confirmStyle="danger"
        impactCount={contacts.length}
        onConfirm={() => { setShowDeleteConfirm(false); handleDeleteConfirmed(); }}
        onCancel={() => setShowDeleteConfirm(false)}
      />
    </View>
  );
}

function InfoRow({ label, value }: { label: string; value: string }) {
  return (
    <View className="flex-row justify-between py-2 border-b border-gray-50">
      <Text className="text-gray-500 text-sm">{label}</Text>
      <Text className="text-charcoal text-sm font-medium">{value}</Text>
    </View>
  );
}
