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<string, string> = {
  ADMIN:       '#7C3AED',
  STAFF:       '#0891B2',
  TECHNICIAN:  '#059669',
  COLLECTOR:   '#D97706',
};
const ROLE_BG: Record<string, string> = {
  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 (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <View style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 20, paddingTop: 16, paddingBottom: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'flex-end' }}>
          <View>
            <TouchableOpacity onPress={() => router.back()} activeOpacity={0.7} style={{ marginBottom: 8 }}>
              <Text style={{ color: '#A5F3FC', fontSize: 15, fontWeight: '600' }}>← Back</Text>
            </TouchableOpacity>
            <Text style={{ color: '#FFF', fontSize: 28, fontWeight: '800' }}>Users</Text>
            <Text style={{ color: '#A5F3FC', fontSize: 14, marginTop: 2 }}>{users.length} members</Text>
          </View>
          <TouchableOpacity
            style={{ backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: 12, paddingHorizontal: 16, paddingVertical: 10 }}
            onPress={() => router.push('/(app)/users/new')}
            activeOpacity={0.7}
          >
            <Text style={{ color: '#FFF', fontWeight: '700', fontSize: 15 }}>+ Add User</Text>
          </TouchableOpacity>
        </View>

        {/* Search */}
        <View style={{ backgroundColor: '#FFF', paddingHorizontal: 16, paddingVertical: 12, borderBottomWidth: 1, borderBottomColor: '#F1F5F9' }}>
          <View style={{ backgroundColor: '#F8FAFC', borderWidth: 1.5, borderColor: '#E2E8F0', borderRadius: 12, flexDirection: 'row', alignItems: 'center', paddingHorizontal: 14 }}>
            <TextInput
              style={{ flex: 1, paddingVertical: 13, fontSize: 16, color: '#0F172A' }}
              placeholder="Search users..."
              placeholderTextColor="#94A3B8"
              value={search}
              onChangeText={setSearch}
            />
            {search.length > 0 && (
              <TouchableOpacity onPress={() => setSearch('')} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <View style={{ width: 20, height: 20, borderRadius: 10, backgroundColor: '#CBD5E1', alignItems: 'center', justifyContent: 'center' }}>
                  <Text style={{ color: '#FFF', fontSize: 12, fontWeight: '800', lineHeight: 14 }}>×</Text>
                </View>
              </TouchableOpacity>
            )}
          </View>
        </View>

        {isLoading ? (
          <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <ActivityIndicator color="#0891B2" size="large" />
          </View>
        ) : (
          <FlatList
            data={users}
            keyExtractor={(item) => item.id}
            refreshControl={<RefreshControl refreshing={isRefetching} onRefresh={refetch} tintColor="#0891B2" />}
            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 (
                <TouchableOpacity
                  style={{ backgroundColor: '#FFF', borderRadius: 16, padding: 18, marginBottom: 12, borderWidth: 1, borderColor: '#F1F5F9', flexDirection: 'row', alignItems: 'center', opacity: item.isActive ? 1 : 0.5 }}
                  onPress={() => router.push(`/(app)/users/${item.id}`)}
                  activeOpacity={0.7}
                >
                  {/* Avatar */}
                  <View style={{ width: 48, height: 48, borderRadius: 24, backgroundColor: roleBg, alignItems: 'center', justifyContent: 'center', marginRight: 14 }}>
                    <Text style={{ fontSize: 16, fontWeight: '800', color: roleColor }}>{initials}</Text>
                  </View>

                  {/* Info */}
                  <View style={{ flex: 1 }}>
                    <View style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 3 }}>
                      <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A', marginRight: 8 }}>
                        {item.firstName} {item.lastName}
                      </Text>
                      {!item.isActive && (
                        <View style={{ borderRadius: 10, paddingHorizontal: 8, paddingVertical: 2, backgroundColor: '#FEE2E2' }}>
                          <Text style={{ fontSize: 11, fontWeight: '700', color: '#DC2626' }}>Inactive</Text>
                        </View>
                      )}
                    </View>
                    <Text style={{ fontSize: 14, color: '#64748B' }}>{item.email}</Text>
                  </View>

                  {/* Role badge */}
                  <View style={{ borderRadius: 20, paddingHorizontal: 10, paddingVertical: 5, backgroundColor: roleBg }}>
                    <Text style={{ fontSize: 12, fontWeight: '700', color: roleColor }}>{role}</Text>
                  </View>
                </TouchableOpacity>
              );
            }}
            ListEmptyComponent={
              <View style={{ alignItems: 'center', paddingVertical: 60 }}>
                <Text style={{ fontSize: 17, color: '#94A3B8' }}>No users found</Text>
              </View>
            }
          />
        )}
      </View>
    </SafeAreaView>
  );
}
