import { useState } from 'react'; import { View, Text, FlatList, TextInput, TouchableOpacity, ActivityIndicator, RefreshControl, Alert } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; import { router } from 'expo-router'; import { api } from '../../../services/api'; const ROLE_COLOR: Record = { ADMIN: '#7C3AED', STAFF: '#0891B2', TECHNICIAN: '#059669', COLLECTOR: '#D97706', }; const ROLE_BG: Record = { ADMIN: '#F5F3FF', STAFF: '#ECFEFF', TECHNICIAN: '#F0FDF4', COLLECTOR: '#FFFBEB', }; export default function UsersScreen() { const [search, setSearch] = useState(''); const qc = useQueryClient(); const { data, isLoading, refetch, isRefetching } = useQuery({ queryKey: ['users'], queryFn: () => api.get('/api/v1/users').then(r => Array.isArray(r.data) ? r.data : r.data?.data ?? []), }); const toggleActive = useMutation({ mutationFn: ({ id, isActive }: { id: string; isActive: boolean }) => api.patch(`/api/v1/users/${id}`, { isActive }), onSuccess: () => qc.invalidateQueries({ queryKey: ['users'] }), onError: () => Alert.alert('Error', 'Could not update user.'), }); const users = (data ?? []).filter((u: any) => `${u.firstName} ${u.lastName} ${u.email}`.toLowerCase().includes(search.toLowerCase()) ); return ( {/* Header */} router.back()} activeOpacity={0.7} style={{ marginBottom: 8 }}> ← Back Users {users.length} members router.push('/(app)/users/new')} activeOpacity={0.7} > + Add User {/* Search */} {search.length > 0 && ( setSearch('')} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}> × )} {isLoading ? ( ) : ( item.id} refreshControl={} contentContainerStyle={{ padding: 16, paddingBottom: 32 }} renderItem={({ item }) => { const role = item.roleAssignments?.[0]?.role ?? 'STAFF'; const roleColor = ROLE_COLOR[role] ?? '#6B7280'; const roleBg = ROLE_BG[role] ?? '#F1F5F9'; const initials = `${item.firstName?.[0] ?? ''}${item.lastName?.[0] ?? ''}`.toUpperCase(); return ( router.push(`/(app)/users/${item.id}`)} activeOpacity={0.7} > {/* Avatar */} {initials} {/* Info */} {item.firstName} {item.lastName} {!item.isActive && ( Inactive )} {item.email} {/* Role badge */} {role} ); }} ListEmptyComponent={ No users found } /> )} ); }