import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/users_management_controller.dart';
import 'add_user_view.dart';

class UsersManagementView extends StatelessWidget {
  const UsersManagementView({super.key});

  @override
  Widget build(BuildContext context) {
    final controller = Get.put(UsersManagementController());
    final isDark = Theme.of(context).brightness == Brightness.dark;

    return Scaffold(
      appBar: AppBar(
        title: const Text('إدارة مستخدمي النظام', style: TextStyle(fontFamily: 'El Messiri')),
        centerTitle: true,
        backgroundColor: const Color(0xFF0F4C81),
        foregroundColor: Colors.white,
        elevation: 0,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh_rounded),
            onPressed: () => controller.fetchUsers(),
          ),
          IconButton(
            icon: const Icon(Icons.person_add),
            onPressed: () async {
              await Get.to(() => const AddUserView());
              controller.fetchUsers();
            },
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.users.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(Icons.people_outline, size: 80, color: Colors.grey.shade400),
                const SizedBox(height: 16),
                const Text('لا يوجد مستخدمين مسجلين', style: TextStyle(fontSize: 18, color: Colors.grey)),
                const SizedBox(height: 16),
                ElevatedButton.icon(
                  onPressed: () async {
                    await Get.to(() => const AddUserView());
                    controller.fetchUsers();
                  },
                  icon: const Icon(Icons.person_add),
                  label: const Text('إضافة مستخدم'),
                  style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F4C81)),
                ),
              ],
            ),
          );
        }

        return RefreshIndicator(
          onRefresh: controller.fetchUsers,
          child: ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: controller.users.length,
            itemBuilder: (context, index) {
              final user = controller.users[index];
              return _buildUserCard(user, controller, isDark, context);
            },
          ),
        );
      }),
    );
  }

  Widget _buildUserCard(Map<String, dynamic> user, UsersManagementController controller, bool isDark, BuildContext context) {
    final role = user['role'] ?? '';
    final isActive = user['is_active'] == 1 || user['is_active'] == true;
    Color roleColor;
    String roleLabel;

    switch (role) {
      case 'super_admin':
        roleColor = const Color(0xFF6366F1);
        roleLabel = 'مدير النظام';
        break;
      case 'admin':
        roleColor = const Color(0xFF0F4C81);
        roleLabel = 'مدير';
        break;
      case 'accountant':
        roleColor = const Color(0xFF10B981);
        roleLabel = 'محاسب';
        break;
      default:
        roleColor = Colors.grey;
        roleLabel = role;
    }

    return Card(
      elevation: 0,
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(14),
        side: BorderSide(color: isDark ? Colors.white10 : Colors.grey.shade200),
      ),
      color: isDark ? const Color(0xFF1E1E2E) : Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(14),
        child: Column(
          children: [
            Row(
              children: [
                // Avatar
                CircleAvatar(
                  radius: 24,
                  backgroundColor: roleColor.withValues(alpha: 0.15),
                  child: Icon(Icons.person, color: roleColor, size: 24),
                ),
                const SizedBox(width: 12),
                // Info
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: Text(
                              user['name'] ?? 'مستخدم',
                              style: TextStyle(
                                fontSize: 16, fontWeight: FontWeight.bold,
                                color: isDark ? Colors.white : const Color(0xFF0F172A),
                              ),
                            ),
                          ),
                          Container(
                            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
                            decoration: BoxDecoration(
                              color: roleColor.withValues(alpha: 0.1),
                              borderRadius: BorderRadius.circular(6),
                            ),
                            child: Text(roleLabel, style: TextStyle(color: roleColor, fontSize: 11, fontWeight: FontWeight.w600)),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Text(
                        user['email'] ?? '',
                        style: TextStyle(fontSize: 13, color: isDark ? Colors.white38 : Colors.grey),
                      ),
                      if (user['phone'] != null && user['phone'].toString().isNotEmpty) ...[
                        const SizedBox(height: 2),
                        Text(
                          user['phone'],
                          style: TextStyle(fontSize: 12, color: isDark ? Colors.white24 : Colors.grey.shade400, fontFamily: 'monospace'),
                        ),
                      ],
                      if (user['tenant_name'] != null) ...[
                        const SizedBox(height: 4),
                        Row(
                          children: [
                            Icon(Icons.account_balance, size: 12, color: isDark ? Colors.white24 : Colors.grey),
                            const SizedBox(width: 4),
                            Text(user['tenant_name'], style: TextStyle(fontSize: 12, color: isDark ? Colors.white38 : Colors.grey)),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
              ],
            ),
            const SizedBox(height: 12),
            // Actions
            Row(
              children: [
                // Active/Inactive toggle
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  decoration: BoxDecoration(
                    color: (isActive ? const Color(0xFF10B981) : Colors.red).withValues(alpha: 0.1),
                    borderRadius: BorderRadius.circular(6),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Icon(isActive ? Icons.check_circle : Icons.block, size: 14, color: isActive ? const Color(0xFF10B981) : Colors.red),
                      const SizedBox(width: 4),
                      Text(isActive ? 'نشط' : 'معطّل', style: TextStyle(fontSize: 11, color: isActive ? const Color(0xFF10B981) : Colors.red, fontWeight: FontWeight.w600)),
                    ],
                  ),
                ),
                const Spacer(),
                // Toggle active
                IconButton(
                  icon: Icon(isActive ? Icons.toggle_on : Icons.toggle_off, color: isActive ? const Color(0xFF10B981) : Colors.grey, size: 28),
                  onPressed: () => controller.toggleUserActive(user['id'], !isActive),
                  tooltip: isActive ? 'تعطيل' : 'تفعيل',
                ),
                // Edit
                IconButton(
                  icon: const Icon(Icons.edit, size: 20, color: Color(0xFF0F4C81)),
                  onPressed: () => _showEditDialog(context, user, controller),
                  tooltip: 'تعديل',
                ),
                // Delete
                IconButton(
                  icon: const Icon(Icons.delete_outline, size: 20, color: Colors.red),
                  onPressed: () => _confirmDelete(context, controller, user['id'], user['name'] ?? ''),
                  tooltip: 'حذف',
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  void _showEditDialog(BuildContext context, Map<String, dynamic> user, UsersManagementController controller) {
    final nameC = TextEditingController(text: user['name'] ?? '');
    final emailC = TextEditingController(text: user['email'] ?? '');
    final phoneC = TextEditingController(text: user['phone'] ?? '');
    var selectedRole = user['role'] ?? 'accountant';

    Get.dialog(
      StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('تعديل بيانات المستخدم', textAlign: TextAlign.center),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _editField('الاسم', nameC, Icons.person),
                _editField('البريد', emailC, Icons.email),
                _editField('الهاتف', phoneC, Icons.phone),
                const SizedBox(height: 4),
                DropdownButtonFormField<String>(
                  value: selectedRole,
                  decoration: InputDecoration(
                    labelText: 'الصلاحية',
                    prefixIcon: const Icon(Icons.security, size: 20),
                    border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
                  ),
                  items: const [
                    DropdownMenuItem(value: 'admin', child: Text('مدير')),
                    DropdownMenuItem(value: 'accountant', child: Text('محاسب')),
                  ],
                  onChanged: (v) => setState(() => selectedRole = v!),
                ),
              ],
            ),
          ),
          actions: [
            TextButton(onPressed: () => Get.back(), child: const Text('إلغاء')),
            ElevatedButton(
              onPressed: () {
                Get.back();
                controller.updateUser(user['id'], {
                  'name': nameC.text,
                  'email': emailC.text,
                  'phone': phoneC.text,
                  'role': selectedRole,
                });
              },
              style: ElevatedButton.styleFrom(backgroundColor: const Color(0xFF0F4C81)),
              child: const Text('حفظ', style: TextStyle(color: Colors.white)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _editField(String label, TextEditingController controller, IconData icon) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: TextField(
        controller: controller,
        textDirection: TextDirection.rtl,
        decoration: InputDecoration(
          labelText: label,
          prefixIcon: Icon(icon, size: 20),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(10)),
          contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        ),
      ),
    );
  }

  void _confirmDelete(BuildContext context, UsersManagementController controller, String id, String name) {
    Get.defaultDialog(
      title: 'حذف المستخدم',
      middleText: 'هل أنت متأكد من حذف "$name" نهائياً؟',
      textConfirm: 'حذف',
      textCancel: 'إلغاء',
      confirmTextColor: Colors.white,
      buttonColor: Colors.red,
      onConfirm: () {
        Get.back();
        controller.deleteUser(id);
      },
    );
  }
}
