import { useState } from 'react';
import { View, Text, TouchableOpacity, ScrollView, Alert, ActivityIndicator, Switch } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useLocalSearchParams, router } from 'expo-router';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
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' };

const ROLES = [
  { value: 'TECHNICIAN', label: 'Technician', desc: 'Field work & installations' },
  { value: 'COLLECTOR',  label: 'Collector',  desc: 'Payments & remittances' },
  { value: 'STAFF',      label: 'Staff',      desc: 'General access' },
  { value: 'ADMIN',      label: 'Admin',      desc: 'Full access + user mgmt' },
];

function InfoRow({ label, value }: { label: string; value?: string | null }) {
  return (
    <View style={{ paddingHorizontal: 20, paddingVertical: 16, borderBottomWidth: 1, borderBottomColor: '#F1F5F9' }}>
      <Text style={{ fontSize: 12, fontWeight: '600', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 4 }}>{label}</Text>
      <Text style={{ fontSize: 17, fontWeight: '500', color: '#0F172A' }}>{value ?? '—'}</Text>
    </View>
  );
}

export default function UserDetailScreen() {
  const { id } = useLocalSearchParams<{ id: string }>();
  const qc = useQueryClient();
  const [editingRole, setEditingRole] = useState(false);
  const [newRole, setNewRole] = useState('');

  const { data: user, isLoading } = useQuery({
    queryKey: ['user', id],
    queryFn: () => api.get(`/api/v1/users/${id}`).then(r => r.data),
  });

  const toggleActive = useMutation({
    mutationFn: (isActive: boolean) => api.patch(`/api/v1/users/${id}`, { isActive }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['user', id] }),
    onError: () => Alert.alert('Error', 'Could not update user status.'),
  });

  const changeRole = useMutation({
    mutationFn: (role: string) => api.patch(`/api/v1/users/${id}`, { role }),
    onSuccess: () => {
      setEditingRole(false);
      qc.invalidateQueries({ queryKey: ['user', id] });
      qc.invalidateQueries({ queryKey: ['users'] });
    },
    onError: () => Alert.alert('Error', 'Could not update role.'),
  });

  if (isLoading) {
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
        <View style={{ flex: 1, backgroundColor: '#F8FAFC', alignItems: 'center', justifyContent: 'center' }}>
          <ActivityIndicator color="#0891B2" size="large" />
        </View>
      </SafeAreaView>
    );
  }

  const role       = user?.roleAssignments?.[0]?.role ?? 'STAFF';
  const roleColor  = ROLE_COLOR[role] ?? '#6B7280';
  const roleBg     = ROLE_BG[role]    ?? '#F1F5F9';
  const initials   = `${user?.firstName?.[0] ?? ''}${user?.lastName?.[0] ?? ''}`.toUpperCase();
  const isActive   = user?.isActive ?? true;
  const lastLogin  = user?.lastLoginAt ? new Date(user.lastLoginAt).toLocaleDateString('en-PH', { month: 'long', day: 'numeric', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : 'Never';

  return (
    <SafeAreaView style={{ flex: 1, backgroundColor: '#0891B2' }} edges={['top']}>
      <ScrollView style={{ flex: 1, backgroundColor: '#F8FAFC' }}>
        {/* Header */}
        <View style={{ backgroundColor: '#0891B2', paddingHorizontal: 16, paddingTop: 12, paddingBottom: 24, alignItems: 'center' }}>
          <TouchableOpacity onPress={() => router.back()} style={{ alignSelf: 'flex-start', marginBottom: 16 }} activeOpacity={0.7}>
            <Text style={{ color: '#A5F3FC', fontSize: 17, fontWeight: '600' }}>← Back</Text>
          </TouchableOpacity>
          <View style={{ width: 72, height: 72, borderRadius: 36, backgroundColor: roleBg, alignItems: 'center', justifyContent: 'center', marginBottom: 12 }}>
            <Text style={{ fontSize: 26, fontWeight: '800', color: roleColor }}>{initials}</Text>
          </View>
          <Text style={{ color: '#FFF', fontSize: 22, fontWeight: '800' }}>{user?.firstName} {user?.lastName}</Text>
          <View style={{ borderRadius: 20, paddingHorizontal: 14, paddingVertical: 6, backgroundColor: roleBg, marginTop: 8 }}>
            <Text style={{ fontSize: 14, fontWeight: '700', color: roleColor }}>{role}</Text>
          </View>
          {!isActive && (
            <View style={{ borderRadius: 20, paddingHorizontal: 14, paddingVertical: 6, backgroundColor: '#FEE2E2', marginTop: 6 }}>
              <Text style={{ fontSize: 13, fontWeight: '700', color: '#DC2626' }}>Inactive Account</Text>
            </View>
          )}
        </View>

        <View style={{ padding: 16 }}>
          {/* Info Card */}
          <View style={{ backgroundColor: '#FFF', borderRadius: 20, borderWidth: 1, borderColor: '#F1F5F9', marginBottom: 16, overflow: 'hidden' }}>
            <InfoRow label="Email" value={user?.email} />
            <InfoRow label="Phone" value={user?.phone} />
            <InfoRow label="Last Login" value={lastLogin} />
            <View style={{ paddingHorizontal: 20, paddingVertical: 16 }}>
              <Text style={{ fontSize: 12, fontWeight: '600', color: '#94A3B8', textTransform: 'uppercase', letterSpacing: 0.4, marginBottom: 12 }}>Account Status</Text>
              <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                <View>
                  <Text style={{ fontSize: 17, fontWeight: '600', color: isActive ? '#166534' : '#DC2626' }}>
                    {isActive ? 'Active' : 'Inactive'}
                  </Text>
                  <Text style={{ fontSize: 13, color: '#94A3B8', marginTop: 2 }}>
                    {isActive ? 'User can log in' : 'Login is blocked'}
                  </Text>
                </View>
                <Switch
                  value={isActive}
                  onValueChange={(val) => Alert.alert(
                    val ? 'Activate User' : 'Deactivate User',
                    val ? `Allow ${user?.firstName} to log in?` : `Block ${user?.firstName} from logging in?`,
                    [
                      { text: 'Cancel', style: 'cancel' },
                      { text: val ? 'Activate' : 'Deactivate', onPress: () => toggleActive.mutate(val), style: val ? 'default' : 'destructive' },
                    ]
                  )}
                  trackColor={{ false: '#E2E8F0', true: '#0891B2' }}
                  thumbColor="#FFF"
                />
              </View>
            </View>
          </View>

          {/* Role Change */}
          <View style={{ backgroundColor: '#FFF', borderRadius: 20, borderWidth: 1, borderColor: '#F1F5F9', marginBottom: 16, overflow: 'hidden' }}>
            <View style={{ paddingHorizontal: 20, paddingVertical: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', borderBottomWidth: editingRole ? 1 : 0, borderBottomColor: '#F1F5F9' }}>
              <Text style={{ fontSize: 16, fontWeight: '700', color: '#0F172A' }}>Role</Text>
              <TouchableOpacity onPress={() => { setEditingRole(!editingRole); setNewRole(role); }} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}>
                <Text style={{ fontSize: 15, fontWeight: '600', color: '#0891B2' }}>{editingRole ? 'Cancel' : 'Change'}</Text>
              </TouchableOpacity>
            </View>
            {editingRole && (
              <View style={{ padding: 16 }}>
                {ROLES.map(r => {
                  const isSelected = (newRole || role) === r.value;
                  const rc = ROLE_COLOR[r.value] ?? '#6B7280';
                  const rb = ROLE_BG[r.value]   ?? '#F1F5F9';
                  return (
                    <TouchableOpacity
                      key={r.value}
                      onPress={() => setNewRole(r.value)}
                      style={{ flexDirection: 'row', alignItems: 'center', borderRadius: 14, padding: 14, marginBottom: 8, borderWidth: 2, borderColor: isSelected ? rc : '#E2E8F0', backgroundColor: isSelected ? rb : '#FFF' }}
                      activeOpacity={0.7}
                    >
                      <View style={{ flex: 1 }}>
                        <Text style={{ fontSize: 15, fontWeight: '700', color: isSelected ? rc : '#0F172A' }}>{r.label}</Text>
                        <Text style={{ fontSize: 13, color: '#64748B' }}>{r.desc}</Text>
                      </View>
                      <View style={{ width: 20, height: 20, borderRadius: 10, borderWidth: 2, borderColor: isSelected ? rc : '#CBD5E1', backgroundColor: isSelected ? rc : 'transparent', alignItems: 'center', justifyContent: 'center' }}>
                        {isSelected && <View style={{ width: 7, height: 7, borderRadius: 4, backgroundColor: '#FFF' }} />}
                      </View>
                    </TouchableOpacity>
                  );
                })}
                <TouchableOpacity
                  style={{ backgroundColor: newRole && newRole !== role ? '#0891B2' : '#CBD5E1', borderRadius: 14, paddingVertical: 16, alignItems: 'center', marginTop: 4 }}
                  onPress={() => newRole && newRole !== role && Alert.alert(
                    'Change Role',
                    `Change ${user?.firstName}'s role to ${newRole}?`,
                    [
                      { text: 'Cancel', style: 'cancel' },
                      { text: 'Change', onPress: () => changeRole.mutate(newRole) },
                    ]
                  )}
                  disabled={changeRole.isPending || !newRole || newRole === role}
                  activeOpacity={0.8}
                >
                  {changeRole.isPending
                    ? <ActivityIndicator color="#FFF" />
                    : <Text style={{ color: '#FFF', fontSize: 16, fontWeight: '700' }}>Apply Role Change</Text>
                  }
                </TouchableOpacity>
              </View>
            )}
          </View>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}
