لماذا يتم تحديث الواجهه بالكامل عند تغيير حالة احد المستخدمين من check الى checked 
للعلم الكود
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:micro_panel/AboutApp.dart';
import 'package:micro_panel/AddHotspotUser.dart';
import 'package:micro_panel/AddUserManagerUser.dart';
import 'package:micro_panel/HelpDesk.dart';
import 'package:micro_panel/HomePage.dart';
import 'package:micro_panel/HotspotProfile.dart';
import 'package:micro_panel/Login.dart';
import 'package:micro_panel/SendNotes.dart';
import 'package:micro_panel/UserManagerProfile.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/backupSN.dart';
import 'package:micro_panel/free_rebiuld.dart';
import 'package:micro_panel/hotspotUserList.dart';
import 'package:path/path.dart' as path;
import 'dart:convert';
import 'package:intl/intl.dart' as intl;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:router_os_client/router_os_client.dart';

class UserManagerUserList extends StatefulWidget {
  final RouterOSClient client;
  const UserManagerUserList({Key? key, required this.client}) : super(key: key);
  @override
  _UserManagerUserListState createState() => _UserManagerUserListState();
}

class _UserManagerUserListState extends State<UserManagerUserList> {
  List<Map<String, dynamic>> _users = [];
  bool _isLoading = true;
  bool _sortAscending = true;
  int _sortColumnIndex = 0;
  String _searchQuery = '';
  int _itemsPerPage = 25;
  int _currentPage = 1;
  int _totalItems = 0;
  bool _searchingAllData = false;
  List<Map<String, dynamic>> _allUsersForSearch = [];
  final TextEditingController _searchController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final TextEditingController _limitBytesController = TextEditingController();
  final TextEditingController _addBytesController = TextEditingController();
  String _selectedUnit = 'MB';
  String _addBytesUnit = 'MB';
  final _searchDebouncer = _Debouncer(milliseconds: 500);
  List<String> _selectedUsers = [];

  final Color _backgroundColor = Color(0xFF0A192F);
  final Color _cardColor = Color(0xFF172A46);
  final Color _primaryColor = Color(0xFF3B82F6);
  final Color _secondaryColor = Color(0xFF10B981);
  final Color _accentColor = Color(0xFFEF4444);
  final Color _textColor = Colors.white;
  final Color _successColor = Color(0xFF10B981);
  final Color _warningColor = Color(0xFFF59E0B);
  final Color _borderColor = Color(0xFF1E293B);
  final Color _surfaceColor = Color(0xFF1E293B);

  bool isHotspotExpanded = false;
  bool isUserManagerExpanded = true;
  bool isSettingsExpanded = false;
  bool isHelpExpanded = false;

  Future<File> _getJsonFile() async {
    final maindirectory = await getApplicationDocumentsDirectory();
    final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
    if (!await saveDirectory.exists()) {
      await saveDirectory.create(recursive: true);
    }
    final filePath = path.join(saveDirectory.path, 'user_manager_users.json');
    return File(filePath);
  }

  Widget _AppBarActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
    required Color color,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 4),
      child: Tooltip(
        message: label,
        child: IconButton(
          icon: Icon(icon, size: 20),
          color: color,
          onPressed: onPressed,
          style: IconButton.styleFrom(
            backgroundColor: color.withOpacity(0.1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            padding: EdgeInsets.all(8),
          ),
        ),
      ),
    );
  }

  Future<File> _getCollapseStateFile() async {
    final maindirectory = await getApplicationDocumentsDirectory();
    final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
    if (!await saveDirectory.exists()) {
      await saveDirectory.create(recursive: true);
    }
    return File('${saveDirectory.path}/collapse_state.json');
  }

  Widget _buildUserCountBanner() {
    final isMobile = MediaQuery.of(context).size.width < 768;

    return Container(
      width: double.infinity,
      margin: EdgeInsets.only(bottom: 16),
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      decoration: BoxDecoration(
        color: _primaryColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _primaryColor.withOpacity(0.4), width: 1.2),
        boxShadow: [
          BoxShadow(
            color: _primaryColor.withOpacity(0.15),
            blurRadius: 6,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.people_alt_rounded,
            size: isMobile ? 26 : 32,
            color: _primaryColor,
          ),
          SizedBox(width: 12),
          Text(
            _searchQuery.isEmpty
                ? 'عدد المستخدمين: ${intl.NumberFormat.decimalPattern().format(_totalItems)}'
                : 'عدد المستخدمين المطابقين: ${intl.NumberFormat.decimalPattern().format(_filteredUsers.length)}',
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: isMobile ? 18 : 22,
              fontWeight: FontWeight.bold,
              color: _primaryColor,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildSearchButton() {
    return ElevatedButton.icon(
      onPressed: () {
        _showSearchDialog();
      },
      icon: Icon(Icons.search, size: 20),
      label: Text('بحث', style: TextStyle(color: Colors.white)),
      style: ElevatedButton.styleFrom(
        backgroundColor: _cardColor,
        foregroundColor: _textColor,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12),
          side: BorderSide(color: _borderColor),
        ),
        elevation: 0,
      ),
    );
  }

  Future<void> _showSearchDialog() async {
    return showDialog(
      context: context,
      builder: (context) {
        return Directionality(
          textDirection: TextDirection.rtl,
          child: AlertDialog(
            backgroundColor: _surfaceColor,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            title: Text(
              'بحث عن مستخدمين',
              style: TextStyle(fontFamily: 'Tajawal', color: _primaryColor),
            ),
            content: _buildSearchBar(), // نستخدم نفس شريط البحث الحالي
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  _searchController.clear();
                },
                child: Text(
                  'إلغاء',
                  style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                ),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context),
                style: ElevatedButton.styleFrom(
                  backgroundColor: _primaryColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text('بحث', style: TextStyle(color: Colors.white)),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _deleteSelectedUsers() async {
    if (_selectedUsers.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('الرجاء تحديد مستخدمين أولاً'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
      return;
    }

    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => Directionality(
            textDirection: TextDirection.rtl,
            child: AlertDialog(
              backgroundColor: _surfaceColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              title: Text(
                'تأكيد الحذف',
                style: TextStyle(fontFamily: 'Tajawal', color: _accentColor),
              ),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف ${_selectedUsers.length} مستخدم؟',
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text(
                    'إلغاء',
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _accentColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Text('حذف', style: TextStyle(color: Colors.white)),
                ),
              ],
            ),
          ),
    );

    if (confirmed == true) {
      try {
        final routerVersion = await _getRouterVersion();
        final isVersion7 = routerVersion >= 7;
        setState(() => _isLoading = true);
        for (var userId in _selectedUsers) {
          await widget.client.talk([
            isVersion7
                ? '/user-manager/user/remove'
                : '/tool/user-manager/user/remove',
            '=.id=$userId',
          ]);
          if (isVersion7) {
            await widget.client.talk([
              '/user-manager/user-profile/remove',
              '=.id=$userId',
            ]);
          }
        }

        final users = await _loadUsersFromJson();
        final updatedUsers =
            users.where((u) => !_selectedUsers.contains(u['.id'])).toList();
        await _saveUsersToJson(updatedUsers);

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم حذف ${_selectedUsers.length} مستخدم بنجاح'),
            backgroundColor: _successColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );

        setState(() {
          _users =
              updatedUsers
                  .skip((_currentPage - 1) * _itemsPerPage)
                  .take(_itemsPerPage)
                  .toList();
          _totalItems = updatedUsers.length;
          _selectedUsers.clear();
          _isLoading = false;
        });
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('خطأ في الحذف'),
            backgroundColor: _accentColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      } finally {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _deleteExpiredUsers() async {
    final routerVersion = await _getRouterVersion();
    final isVersion7 = routerVersion >= 7;

    try {
      setState(() => _isLoading = true);

      final allUsers = await _loadUsersFromJson();

      // تحديد المستخدمين المراد حذفهم
      final usersToDelete =
          allUsers.where((user) {
            final hasNoProfile =
                (user['actual-profile'] == null ||
                    user['actual-profile'].toString().isEmpty) &&
                (user['profile'] == null || user['profile'].toString().isEmpty);
            final isUsedState = user['state'] == 'used';
            return hasNoProfile || isUsedState;
          }).toList();

      if (usersToDelete.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('لا يوجد مستخدمين منتهية صلاحيتهم للحذف'),
            backgroundColor: _warningColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
        return;
      }

      for (var user in usersToDelete) {
        final userId = user['.id'] as String;
        final username = user['name'] ?? user['username'];

        if (username != null && username.toString().isNotEmpty) {
          // حذف الجلسات المرتبطة بالمستخدم
          final sessions = await widget.client.talk([
            isVersion7
                ? '/user-manager/session/print'
                : '/tool/user-manager/session/print',
            '?user=$username',
          ]);

          for (var session in sessions) {
            final sessionId = session['.id'];
            if (sessionId != null) {
              await widget.client.talk([
                isVersion7
                    ? '/user-manager/session/remove'
                    : '/tool/user-manager/session/remove',
                '=.id=$sessionId',
              ]);
            }
          }
        }

        // حذف user-profile إذا كان إصدار 7 وحالة المستخدم used
        if (isVersion7 && user['state'] == 'used') {
          await widget.client.talk([
            '/user-manager/user-profile/remove',
            '=.id=$userId',
          ]);
        }

        // حذف المستخدم
        await widget.client.talk([
          isVersion7
              ? '/user-manager/user/remove'
              : '/tool/user-manager/user/remove',
          '=.id=$userId',
        ]);
      }

      // تحديث قائمة المستخدمين محليًا
      final updatedUsers =
          allUsers
              .where(
                (user) =>
                    !usersToDelete.map((u) => u['.id']).contains(user['.id']),
              )
              .toList();
      await _saveUsersToJson(updatedUsers);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'تم حذف ${usersToDelete.length} مستخدم منتهي الصلاحية مع الجلسات',
          ),
          backgroundColor: _successColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );

      _loadUsers(page: _currentPage);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء حذف المستخدمين المنتهية صلاحيتهم'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
      print('$e');
    } finally {
      setState(() => _isLoading = false);
    }
  }

  Future<int> _getRouterVersion() async {
    try {
      final maindirectory = await getApplicationDocumentsDirectory();
      final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
      if (!await saveDirectory.exists()) {
        await saveDirectory.create(recursive: true);
      }
      final file = File('${saveDirectory.path}/router_version.json');

      if (await file.exists()) {
        final content = await file.readAsString();

        // تحويل JSON إلى كائن Dart وطباعة المفتاح
        final jsonData = jsonDecode(content);
        print('البيانات المحلولة من JSON: $jsonData');
        print('الإصدار الموجود في الملف: ${jsonData['router_version']}');

        return int.tryParse(jsonData['router_version'].toString()) ?? 6;
      }

      print('الملف غير موجود، سيتم استخدام الإصدار الافتراضي.');
      return 6;
    } catch (e) {
      print('حدث خطأ أثناء قراءة ملف الإصدار');
      return 6;
    }
  }

  Future<void> _saveUsersToJson(List<Map<String, dynamic>> users) async {
    final file = await _getJsonFile();
    await file.writeAsString(jsonEncode(users));
  }

  Future<List<Map<String, dynamic>>> _loadUsersFromJson() async {
    final routerVersion = await _getRouterVersion();
    try {
      final file = await _getJsonFile();
      if (!await file.exists()) return [];
      final jsonData = await file.readAsString();
      final users = List<Map<String, dynamic>>.from(jsonDecode(jsonData));
      return users
          .map((user) {
            // توحيد المفاتيح
            if (routerVersion >= 7 && user['name'] != null) {
              user['username'] = user['name'];
            }
            // التأكد من وجود مفتاح البروفايل
            if (user['profile'] != null && user['actual-profile'] == null) {
              user['actual-profile'] = user['profile'];
            }
            return user;
          })
          .where((user) {
            final hasId =
                user['.id'] != null && user['.id'].toString().isNotEmpty;
            final hasName =
                user['username'] != null &&
                user['username'].toString().isNotEmpty;
            return hasId && hasName;
          })
          .toList();
    } catch (e) {
      print('Error loading users from JSON: $e');
      return [];
    }
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(milliseconds: 100), () {
      _loadUsersFromJson().then((users) {
        setState(() {
          _users = users.take(_itemsPerPage).toList();

          _totalItems = users.length;
          _isLoading = false;
        });
      });
      _searchController.addListener(_handleSearch);
      _scrollController.addListener(_scrollListener);
      _loadTotalUsers();
    });
  }

  @override
  void dispose() {
    _searchController.removeListener(_handleSearch);
    _searchDebouncer.dispose();
    _scrollController.dispose();
    _limitBytesController.dispose();
    _addBytesController.dispose();
    super.dispose();
  }

  Future<void> _loadTotalUsers() async {
    try {
      final users = await _loadUsersFromJson();
      setState(() => _totalItems = users.length);
    } catch (e) {
      setState(() => _totalItems = 0);
    }
  }

  void _handleSearch() {
    _searchDebouncer.run(() {
      final newQuery = _searchController.text.trim();
      setState(() {
        _searchQuery = newQuery;
        _currentPage = 1; // إعادة التعيين إلى الصفحة الأولى عند تغيير البحث
      });

      // إذا كان البحث فارغاً، ارجع إلى العرض العادي مع Pagination
      if (_searchQuery.isEmpty) {
        _loadUsers(page: 1);
        return;
      }

      // إذا كان هناك بحث، قم بتحميل الصفحة الأولى من النتائج
      _loadSearchResults(page: 1);
    });
  }

  Future<void> _loadSearchResults({int page = 1}) async {
    setState(() => _isLoading = true);
    try {
      final allUsers = await _loadUsersFromJson();
      final searchLower = _searchQuery.toLowerCase();

      // تصفية جميع النتائج مرة واحدة (يمكن تحسين هذا ليكون على الخادم في المستقبل)
      final filteredUsers =
          allUsers.where((user) {
            final name = user['username']?.toString().toLowerCase() ?? '';
            final profile =
                user['actual-profile']?.toString().toLowerCase() ?? '';
            final id = _formatId(user['.id']).toLowerCase();
            return name.contains(searchLower) ||
                profile.contains(searchLower) ||
                id.contains(searchLower);
          }).toList();

      final total = filteredUsers.length;
      final offset = (page - 1) * _itemsPerPage;
      final end = offset.clamp(0, total) + _itemsPerPage;
      final paginatedResults = filteredUsers.sublist(
        offset.clamp(0, total),
        end.clamp(0, total),
      );

      setState(() {
        _users = paginatedResults;
        _totalItems = total;
        _isLoading = false;
        _currentPage = page;
      });

      if (_scrollController.hasClients) {
        _scrollController.jumpTo(0);
      }
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('خطأ في البحث'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    }
  }

  void _scrollListener() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      if ((_currentPage - 1) * _itemsPerPage + _users.length < _totalItems) {
        _loadUsers(page: _currentPage + 1);
      }
    }
  }

  Future<void> _loadUsers({int page = 1, bool loadAllForSearch = false}) async {
    if (_isLoading || _searchingAllData)
      return; // إضافة هذا لمنع استدعاءات التداخل

    if (loadAllForSearch) {
      setState(() => _searchingAllData = true);
      try {
        _allUsersForSearch = await _loadUsersFromJson();
      } catch (e) {
        // معالجة الخطأ إذا أردت
      } finally {
        setState(() => _searchingAllData = false);
      }
      return;
    }

    setState(() => _isLoading = true);
    try {
      final users = await _loadUsersFromJson();
      final total = users.length;
      final offset = (page - 1) * _itemsPerPage;
      final end = (offset + _itemsPerPage).clamp(0, total);
      final paginatedUsers = users.sublist(offset.clamp(0, total), end);

      // تحديث الحالة دفعة واحدة لتقليل إعادة البناء المتكررة
      setState(() {
        _users = paginatedUsers;
        _totalItems = total;
        _currentPage = page;
        _isLoading = false; // وضع false هنا بعد تحديث كل المتغيرات
      });

      // استخدام animateTo بدلاً من jumpTo لتقليل الإزعاج البصري
      if (_scrollController.hasClients) {
        await _scrollController.animateTo(
          0,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('خطأ في جلب البيانات'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    }
  }

  String _formatBytes(String? bytesStr) {
    if (bytesStr == null || bytesStr.isEmpty) return '0 B';

    try {
      final bytes = int.tryParse(bytesStr) ?? 0;
      if (bytes <= 0) return '0 B';

      const units = ['B', 'KB', 'MB', 'GB', 'TB'];
      int digitGroups = (log(bytes) / log(1024)).floor();

      return '${(bytes / pow(1024, digitGroups)).toStringAsFixed(1)} ${units[digitGroups]}';
    } catch (e) {
      return bytesStr;
    }
  }

  String _formatUptime(String? uptime) {
    if (uptime == null || uptime.isEmpty) return 'لم يبدى الاستخدام بعد';
    try {
      final parts = uptime.split(':');
      if (parts.length != 3) return uptime;
      final hours = parts[0].padLeft(2, '0');
      final minutes = parts[1].padLeft(2, '0');
      final seconds = parts[2].padLeft(2, '0');
      return '$hours:$minutes:$seconds';
    } catch (e) {
      return uptime;
    }
  }

  String _formatId(String? id) {
    if (id == null || id.isEmpty) return 'غير معروف';
    try {
      if (id.startsWith('*')) {
        return int.parse(id.substring(1), radix: 16).toString();
      }
      return id;
    } catch (e) {
      return id;
    }
  }

  Future<void> _toggleUserStatus(Map<String, dynamic> user) async {
    final routerVersion = await _getRouterVersion();
    final isVersion7 = routerVersion >= 7;
    final currentStatus = user['disabled'] == 'true';
    final newStatus = currentStatus ? 'false' : 'true';
    try {
      await widget.client.talk([
        isVersion7 ? '/user-manager/user/set' : '/tool/user-manager/user/set',
        '=.id=${user['.id']}',
        '=disabled=$newStatus',
      ]);

      final users = await _loadUsersFromJson();
      final updatedUsers =
          users.map((u) {
            if (u['.id'] == user['.id']) {
              return {...u, 'disabled': newStatus};
            }
            return u;
          }).toList();

      await _saveUsersToJson(updatedUsers);

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            '${user['username']} تم ${newStatus == 'true' ? 'تعطيل' : 'تفعيل'} المستخدم',
          ),
          backgroundColor: _successColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );

      _loadUsers(page: _currentPage);
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('خطأ في تعديل الحالة'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
      print('$e');
    }
  }

  Future<void> _confirmDeleteUser(Map<String, dynamic> user) async {
    final routerVersion = await _getRouterVersion();
    final isVersion7 = routerVersion >= 7;
    final confirmed = await showDialog<bool>(
      context: context,
      builder:
          (context) => Directionality(
            textDirection: TextDirection.rtl,
            child: AlertDialog(
              backgroundColor: _surfaceColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              title: Text(
                'تأكيد الحذف',
                style: TextStyle(fontFamily: 'Tajawal', color: _accentColor),
              ),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف المستخدم "${user['username']}"؟',
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text(
                    'إلغاء',
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                  ),
                ),
                ElevatedButton(
                  onPressed: () async {
                    try {
                      // حذف المستخدم مباشرة باستخدام الـ ID
                      await widget.client.talk([
                        isVersion7
                            ? '/user-manager/user/remove'
                            : '/tool/user-manager/user/remove',
                        '=.id=${user['.id']}',
                      ]);
                      if (isVersion7) {
                        await widget.client.talk([
                          '/user-manager/user-profile/remove',
                          '=.id=${user['.id']}',
                        ]);
                      }
                      // تحديث القائمة المحلية بعد الحذف
                      final users = await _loadUsersFromJson();
                      final updatedUsers =
                          users.where((u) => u['.id'] != user['.id']).toList();
                      await _saveUsersToJson(updatedUsers);

                      Navigator.pop(context, true);

                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('تم حذف المستخدم بنجاح'),
                          backgroundColor: _successColor,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      );

                      setState(() {
                        _users =
                            updatedUsers
                                .skip((_currentPage - 1) * _itemsPerPage)
                                .take(_itemsPerPage)
                                .toList();
                        _totalItems = updatedUsers.length;
                      });
                    } catch (e) {
                      Navigator.pop(context, false);
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('خطأ في الحذف'),
                          backgroundColor: _accentColor,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      );
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _accentColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Text('حذف', style: TextStyle(color: Colors.white)),
                ),
              ],
            ),
          ),
    );
  }

  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: TextStyle(
              fontFamily: 'Tajawal',
              color: _textColor.withOpacity(0.7),
              fontWeight: FontWeight.bold,
              fontSize: 14,
            ),
          ),
          SizedBox(height: 4),
          Container(
            width: double.infinity,
            padding: EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: _cardColor,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: _borderColor),
            ),
            child: Text(
              value,
              style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUserCountCard() {
    final isMobile = MediaQuery.of(context).size.width < 768;

    return Container(
      padding: EdgeInsets.all(isMobile ? 12 : 16),
      decoration: BoxDecoration(
        color: _primaryColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _primaryColor.withOpacity(0.3)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              Icon(
                Icons.people_alt_rounded,
                size: isMobile ? 24 : 30,
                color: _primaryColor,
              ),
              SizedBox(width: isMobile ? 8 : 16),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'المستخدمين',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      fontSize: isMobile ? 12 : 14,
                      color: _textColor.withOpacity(0.8),
                    ),
                  ),
                  Text(
                    intl.NumberFormat.decimalPattern().format(_totalItems),
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      fontSize: isMobile ? 18 : 24,
                      fontWeight: FontWeight.bold,
                      color: _primaryColor,
                    ),
                  ),
                ],
              ),
            ],
          ),
          if (!isMobile) // إخفاء زر التحديث على الهاتف
            ElevatedButton.icon(
              onPressed: () => _loadUsers(page: _currentPage),
              icon: Icon(Icons.refresh_rounded, size: 20),
              label: Text('تحديث'),
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(
                  horizontal: isMobile ? 12 : 16,
                  vertical: isMobile ? 8 : 12,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildSearchBar() {
    return Container(
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 6,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          filled: true,
          fillColor: _cardColor,
          labelText: 'ابحث عن مستخدم',
          hintText: 'اسم / ID / بروفايل...',
          hintStyle: TextStyle(
            fontFamily: 'Tajawal',
            color: _textColor.withOpacity(0.5),
          ),
          labelStyle: TextStyle(
            fontFamily: 'Tajawal',
            color: _textColor.withOpacity(0.7),
          ),
          prefixIcon: Icon(Icons.search, color: _primaryColor),
          suffixIcon:
              _searchQuery.isNotEmpty
                  ? IconButton(
                    icon: Icon(Icons.close, color: _textColor.withOpacity(0.5)),
                    onPressed: () => _searchController.clear(),
                  )
                  : null,
          border: OutlineInputBorder(
            borderSide: BorderSide.none,
            borderRadius: BorderRadius.circular(12),
          ),
        ),
        style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
      ),
    );
  }

  Widget _buildItemsPerPageControl() {
    return Container(
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: _borderColor),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 6,
            offset: Offset(0, 2),
          ),
        ],
      ),
      padding: EdgeInsets.symmetric(horizontal: 12),
      child: DropdownButton<int>(
        dropdownColor: _surfaceColor,
        underline: SizedBox(),
        value: _itemsPerPage,
        items:
            [10, 25, 50, 100].map((value) {
              return DropdownMenuItem<int>(
                value: value,
                child: Text(
                  '$value عناصر',
                  style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                ),
              );
            }).toList(),
        onChanged: (value) {
          setState(() {
            _itemsPerPage = value!;
            _currentPage = 1;
          });
          _loadUsers(page: 1);
        },
      ),
    );
  }

  Widget _buildLoadingIndicator() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(_primaryColor),
          ),
          SizedBox(height: 16),
          Text(
            _searchingAllData ? "جاري البحث..." : "جاري التحميل...",
            style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
          ),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.person_outline,
            size: 80,
            color: _textColor.withOpacity(0.3),
          ),
          SizedBox(height: 16),
          Text(
            'لا يوجد مستخدمين',
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: _textColor.withOpacity(0.6),
            ),
          ),
          SizedBox(height: 8),
          Text(
            'جرب إضافة مستخدمين جدد.',
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: 14,
              color: _textColor.withOpacity(0.5),
            ),
          ),
        ],
      ),
    );
  }

  List<Map<String, dynamic>> get _filteredUsers {
    if (_searchQuery.isEmpty) return _users;
    final searchLower = _searchQuery.toLowerCase();
    final sourceList =
        _searchingAllData || _allUsersForSearch.isNotEmpty
            ? _allUsersForSearch
            : _users;
    return sourceList.where((user) {
      final name = user['username']?.toString().toLowerCase() ?? '';
      final profile = user['actual-profile']?.toString().toLowerCase() ?? '';
      final id = _formatId(user['.id']).toLowerCase();
      return name.contains(searchLower) ||
          profile.contains(searchLower) ||
          id.contains(searchLower);
    }).toList();
  }

  void _sortUsers(int columnIndex, bool ascending) {
    // التعديل ليتناسب مع خصائص user-manager
    setState(() => _isLoading = true);
    try {
      final List<Map<String, dynamic>> allUsers = [..._users];
      allUsers.sort((a, b) {
        dynamic aValue;
        dynamic bValue;
        switch (columnIndex) {
          case 0:
            aValue = _formatId(a['.id']);
            bValue = _formatId(b['.id']);
            break;
          case 1:
            aValue = a['username']?.toString().toLowerCase() ?? '';
            bValue = b['username']?.toString().toLowerCase() ?? '';
            break;
          case 2:
            aValue = a['actual-profile']?.toString().toLowerCase() ?? '';
            bValue = b['actual-profile']?.toString().toLowerCase() ?? '';
            break;
          case 3:
            aValue = a['disabled'] == 'true' ? 0 : 1;
            bValue = b['disabled'] == 'true' ? 0 : 1;
            break;
          default:
            return 0;
        }

        if (aValue == null || bValue == null) return 0;
        if (aValue is String && bValue is String) {
          return ascending
              ? aValue.compareTo(bValue)
              : bValue.compareTo(aValue);
        } else if (aValue is num && bValue is num) {
          return ascending
              ? aValue.compareTo(bValue)
              : bValue.compareTo(aValue);
        }
        return 0;
      });
      setState(() {
        _users = allUsers;
        _isLoading = false;
        _sortColumnIndex = columnIndex;
        _sortAscending = ascending;
      });
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('خطأ في فرز البيانات'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    }
  }

  int _parseUptimeToSeconds(String? uptime) {
    if (uptime == null || uptime.isEmpty) return 0;
    try {
      final parts = uptime.split(':');
      if (parts.length != 3) return 0;
      final hours = int.tryParse(parts[0]) ?? 0;
      final minutes = int.tryParse(parts[1]) ?? 0;
      final seconds = int.tryParse(parts[2]) ?? 0;
      return hours * 3600 + minutes * 60 + seconds;
    } catch (e) {
      return 0;
    }
  }

  Widget _buildDesktopTable() {
    final usersToDisplay = _searchQuery.isNotEmpty ? _filteredUsers : _users;

    return Column(
      children: [
        Expanded(
          child: LayoutBuilder(
            builder: (context, constraints) {
              return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: ConstrainedBox(
                  constraints: BoxConstraints(minWidth: constraints.maxWidth),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: DataTable(
                      headingRowColor: MaterialStateProperty.resolveWith(
                        (states) => _cardColor,
                      ),
                      headingTextStyle: TextStyle(
                        fontFamily: 'Tajawal',
                        fontWeight: FontWeight.bold,
                        color: _primaryColor,
                      ),
                      dataRowColor: MaterialStateProperty.resolveWith(
                        (states) => _surfaceColor,
                      ),
                      dividerThickness: 0,
                      columnSpacing: 16,
                      sortColumnIndex: _sortColumnIndex,
                      sortAscending: _sortAscending,
                      columns: [
                        DataColumn(label: Text('تحديد')),
                        DataColumn(
                          label: Text('ID'),
                          numeric: true,
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('اسم المستخدم'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('البروفايل'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('التحميل'),
                          numeric: true,
                          tooltip: 'البيانات المحملة',
                        ),
                        DataColumn(
                          label: Text('الرفع'),
                          numeric: true,
                          tooltip: 'البيانات المرفوعة',
                        ),
                        DataColumn(label: Text('الحالة')),
                        DataColumn(label: Text('الإجراءات')),
                      ],
                      rows:
                          usersToDisplay.map((user) {
                            final isDisabled = user['disabled'] == 'true';
                            final state = user['state']?.toString();
                            return DataRow(
                              cells: [
                                DataCell(
                                  Checkbox(
                                    value: _selectedUsers.contains(user['.id']),
                                    onChanged: (bool? value) {
                                      setState(() {
                                        if (value == true) {
                                          _selectedUsers.add(user['.id']);
                                        } else {
                                          _selectedUsers.remove(user['.id']);
                                        }
                                      });
                                    },
                                    activeColor: _primaryColor,
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 80),
                                    padding: EdgeInsets.all(4),
                                    decoration: BoxDecoration(
                                      color: _cardColor,
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      _formatId(user['.id']),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 120),
                                    child: Text(
                                      user['username'] ?? 'غير معروف',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          (() {
                                            if (state == 'used') {
                                              return Colors.red.withOpacity(
                                                0.1,
                                              );
                                            } else if (state ==
                                                'running active') {
                                              return Colors.green.withOpacity(
                                                0.1,
                                              );
                                            } else if (user['actual-profile'] ==
                                                    null ||
                                                (user['actual-profile'] ??
                                                        user['profile'])!
                                                    .toString()
                                                    .isEmpty) {
                                              return Colors.red.withOpacity(
                                                0.1,
                                              );
                                            } else {
                                              return _secondaryColor
                                                  .withOpacity(0.1);
                                            }
                                          })(),
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(
                                        color:
                                            (() {
                                              if (state == 'used') {
                                                return Colors.red.withOpacity(
                                                  0.3,
                                                );
                                              } else if (state ==
                                                  'running active') {
                                                return Colors.green.withOpacity(
                                                  0.3,
                                                );
                                              } else if (user['actual-profile'] ==
                                                      null ||
                                                  (user['actual-profile'] ??
                                                          user['profile'])!
                                                      .toString()
                                                      .isEmpty) {
                                                return Colors.red.withOpacity(
                                                  0.3,
                                                );
                                              } else {
                                                return _secondaryColor
                                                    .withOpacity(0.3);
                                              }
                                            })(),
                                      ),
                                    ),
                                    child: Text(
                                      (() {
                                        if (state == 'used') {
                                          return 'منتهي';
                                        } else if (state == 'running active') {
                                          return 'نشط';
                                        } else if (user['actual-profile'] ==
                                                null ||
                                            (user['actual-profile'] ??
                                                    user['profile'])!
                                                .toString()
                                                .isEmpty) {
                                          return 'منتهي';
                                        } else {
                                          return (user['actual-profile'] ??
                                                      user['profile'])
                                                  ?.toString() ??
                                              'غير معروف';
                                        }
                                      })(),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color:
                                            (() {
                                              if (state == 'used') {
                                                return Colors.red;
                                              } else if (state ==
                                                  'running active') {
                                                return Colors.green;
                                              } else if (user['actual-profile'] ==
                                                      null ||
                                                  (user['actual-profile'] ??
                                                          user['profile'])!
                                                      .toString()
                                                      .isEmpty) {
                                                return Colors.red;
                                              } else {
                                                return _secondaryColor;
                                              }
                                            })(),
                                      ),
                                    ),
                                  ),
                                ),

                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(
                                        user['download-used']?.toString() ??
                                            '0',
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _successColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(
                                        user['upload-used']?.toString() ?? '0',
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _accentColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      (() {
                                        final lastSeen =
                                            user['last-seen']?.toString();
                                        final state = user['state']?.toString();

                                        if (lastSeen == 'never') {
                                          return 'جديد';
                                        } else if (lastSeen == null &&
                                            state == 'waiting') {
                                          return 'جديد';
                                        } else if (lastSeen != null &&
                                            lastSeen != 'never') {
                                          return 'نشط';
                                        } else {
                                          // ترجمة حالات إضافية
                                          if (state == 'used') {
                                            return 'منتهي';
                                          } else if (state ==
                                              'running active') {
                                            return 'نشط';
                                          } else {
                                            return 'مستخدم';
                                          }
                                        }
                                      })(),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),

                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 180),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        SizedBox(width: 8),
                                        Tooltip(
                                          message:
                                              isDisabled
                                                  ? 'تفعيل المستخدم'
                                                  : 'تعطيل المستخدم',
                                          child: InkWell(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                            onTap:
                                                () => _toggleUserStatus(user),
                                            child: Container(
                                              padding: EdgeInsets.all(6),
                                              decoration: BoxDecoration(
                                                color:
                                                    isDisabled
                                                        ? Colors.green
                                                            .withOpacity(0.1)
                                                        : Colors.red
                                                            .withOpacity(0.1),
                                                borderRadius:
                                                    BorderRadius.circular(20),
                                              ),
                                              child: Icon(
                                                isDisabled
                                                    ? Icons.toggle_off
                                                    : Icons.toggle_on,
                                                size: 20,
                                                color:
                                                    isDisabled
                                                        ? Colors.green
                                                        : Colors.red,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(width: 8),
                                        Tooltip(
                                          message: 'حذف المستخدم',
                                          child: InkWell(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                            onTap:
                                                () => _confirmDeleteUser(user),
                                            child: Container(
                                              padding: EdgeInsets.all(6),
                                              decoration: BoxDecoration(
                                                color: _accentColor.withOpacity(
                                                  0.1,
                                                ),
                                                borderRadius:
                                                    BorderRadius.circular(20),
                                              ),
                                              child: Icon(
                                                Icons.delete_outline,
                                                size: 20,
                                                color: _accentColor,
                                              ),
                                            ),
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              ],
                            );
                          }).toList(),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildMobileList() {
    final usersToDisplay = _searchQuery.isNotEmpty ? _filteredUsers : _users;

    return ListView.separated(
      itemCount: usersToDisplay.length,
      padding: EdgeInsets.symmetric(vertical: 5, horizontal: 3),
      separatorBuilder: (context, index) => SizedBox(height: 8),
      itemBuilder: (context, index) {
        final user = usersToDisplay[index];
        final isDisabled = user['disabled'] == 'true';
        final uptime = _formatUptime(user['uptime']);
        final limitBytes = _formatBytes(
          user['limit-bytes-total']?.toString() ?? '0',
        );
        final bytesIn = _formatBytes(user['bytes-in']?.toString() ?? '0');
        final bytesOut = _formatBytes(user['bytes-out']?.toString() ?? '0');
        final usagePercentage = _calculateUsagePercentage(user);

        return Card(
          elevation: 0,
          margin: EdgeInsets.zero,
          color: _cardColor,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
            side: BorderSide(
              color: Theme.of(context).dividerColor.withOpacity(0.1),
              width: 1,
            ),
          ),
          child: Theme(
            data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
            child: ExpansionTile(
              backgroundColor: _cardColor,
              collapsedBackgroundColor: _cardColor,
              tilePadding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              childrenPadding: EdgeInsets.all(12),
              leading: _buildUserAvatar(user),
              title: _buildUserName(user, isDisabled),
              subtitle: _buildUserSubtitle(user),
              trailing: _buildUserStatusIndicator(isDisabled),
              collapsedIconColor: Theme.of(
                context,
              ).iconTheme.color?.withOpacity(0.6),
              iconColor: Theme.of(context).primaryColor,
              children: [
                _buildUsageProgress(usagePercentage),
                SizedBox(height: 16),
                _buildDataStatsGrid(bytesIn, bytesOut, limitBytes),
                SizedBox(height: 16),
                _buildUptimeTile(uptime),
                SizedBox(height: 16),
                _buildActionButtons(user, isDisabled),
              ],
            ),
          ),
        );
      },
    );
  }

  Widget _buildUserAvatar(Map<String, dynamic> user) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          width: 36,
          height: 36,
          decoration: BoxDecoration(
            shape: BoxShape.circle,
            color: _primaryColor.withOpacity(0.08),
          ),
        ),
        Transform.scale(
          scale: 0.8,
          child: Checkbox(
            value: _selectedUsers.contains(user['.id']),
            onChanged: (bool? value) => _handleUserSelection(user, value),
            activeColor: _primaryColor,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            visualDensity: VisualDensity.compact,
            shape: CircleBorder(),
          ),
        ),
      ],
    );
  }

  Widget _buildUserName(Map<String, dynamic> user, bool isDisabled) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          user['username'] ?? 'غير معروف',
          style: TextStyle(
            fontFamily: 'Tajawal',
            fontSize: 16,
            fontWeight: FontWeight.w700,
            color: isDisabled ? Colors.grey[500] : _textColor,
            height: 1.2,
          ),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        SizedBox(height: 4),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
          decoration: BoxDecoration(
            color: _cardColor.withOpacity(0.3),
            borderRadius: BorderRadius.circular(4),
            border: Border.all(
              color: _primaryColor.withOpacity(0.3),
              width: 0.5,
            ),
          ),
          child: Text(
            _formatId(user['.id'] ?? ''),
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: 10,
              color: _primaryColor,
              fontWeight: FontWeight.w500,
            ),
          ),
        ),
      ],
    );
  }

  Widget _buildUserSubtitle(Map<String, dynamic> user) {
    final isDisabled = user['disabled'] == 'true';
    final state = user['state']?.toString();
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color:
            (() {
              if (state == 'used') {
                return Colors.red.withOpacity(0.1);
              } else if (state == 'running active') {
                return Colors.green.withOpacity(0.1);
              } else if (user['actual-profile'] == null ||
                  (user['actual-profile'] ?? user['profile'])!
                      .toString()
                      .isEmpty) {
                return Colors.red.withOpacity(0.1);
              } else if (isDisabled) {
                return Colors.grey.withOpacity(0.1);
              } else {
                return _secondaryColor.withOpacity(0.1);
              }
            })(),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color:
              (() {
                if (state == 'used') {
                  return Colors.red.withOpacity(0.3);
                } else if (state == 'running active') {
                  return Colors.green.withOpacity(0.3);
                } else if (user['actual-profile'] == null ||
                    (user['actual-profile'] ?? user['profile'])!
                        .toString()
                        .isEmpty) {
                  return Colors.red.withOpacity(0.3);
                } else if (isDisabled) {
                  return Colors.grey.withOpacity(0.3);
                } else {
                  return _secondaryColor.withOpacity(0.3);
                }
              })(),
        ),
      ),

      child: Text(
        (() {
          if (state == 'used') {
            return 'منتهي';
          } else if (state == 'running active') {
            return 'نشط';
          } else if (user['actual-profile'] == null ||
              (user['actual-profile'] ?? user['profile'])!.toString().isEmpty) {
            return 'منتهي';
          } else {
            return (user['actual-profile'] ?? user['profile'])?.toString() ??
                'غير معروف';
          }
        })(),
        style: TextStyle(
          fontFamily: 'Tajawal',
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color:
              (() {
                if (state == 'used') {
                  return Colors.red;
                } else if (state == 'running active') {
                  return Colors.green;
                } else if (user['actual-profile'] == null ||
                    (user['actual-profile'] ?? user['profile'])!
                        .toString()
                        .isEmpty) {
                  return Colors.red;
                } else if (isDisabled) {
                  return Colors.grey;
                } else {
                  return _secondaryColor;
                }
              })(),
        ),

        textAlign: TextAlign.center,
      ),
    );
  }

  Widget _buildUserStatusIndicator(bool isDisabled) {
    return Tooltip(
      message: isDisabled ? 'معطل' : 'نشط',
      child: Container(
        width: 28,
        height: 28,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color:
              isDisabled
                  ? Colors.red.withOpacity(0.1)
                  : _successColor.withOpacity(0.1),
        ),
        child: Icon(
          isDisabled ? Icons.block : Icons.check_circle,
          size: 16,
          color: isDisabled ? Colors.red : _successColor,
        ),
      ),
    );
  }

  Widget _buildUsageProgress(double usagePercentage) {
    return Container(
      padding: EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Theme.of(context).cardColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'استهلاك البيانات',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  fontSize: 13,
                  color: _textColor.withOpacity(0.8),
                ),
              ),
              Text(
                '${(usagePercentage * 100).toStringAsFixed(1)}%',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  fontSize: 13,
                  fontWeight: FontWeight.bold,
                  color: usagePercentage > 0.8 ? Colors.orange : _primaryColor,
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: LinearProgressIndicator(
              value: usagePercentage,
              backgroundColor: _borderColor.withOpacity(0.1),
              color: usagePercentage > 0.8 ? Colors.orange : _primaryColor,
              minHeight: 6,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDataStatsGrid(
    String bytesIn,
    String bytesOut,
    String limitBytes,
  ) {
    return GridView.count(
      crossAxisCount: 3,
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      childAspectRatio: 1.3,
      mainAxisSpacing: 8,
      crossAxisSpacing: 8,
      children: [
        _buildDataStatItem(
          icon: Icons.download,
          label: 'التحميل',
          value: bytesIn,
          color: _successColor,
        ),
        _buildDataStatItem(
          icon: Icons.upload,
          label: 'الرفع',
          value: bytesOut,
          color: _accentColor,
        ),
        _buildDataStatItem(
          icon: Icons.language,
          label: 'الحد الأقصى',
          value: limitBytes,
          color: _warningColor,
        ),
      ],
    );
  }

  Widget _buildDataStatItem({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Container(
      padding: EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: color.withOpacity(0.05),
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: color.withOpacity(0.15), width: 1),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 18, color: color),
          SizedBox(height: 6),
          Text(
            value,
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: 12,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: 2),
          Text(
            label,
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: 10,
              color: _textColor.withOpacity(0.6),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildUptimeTile(String uptime) {
    return ListTile(
      contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
      leading: Container(
        width: 36,
        height: 36,
        decoration: BoxDecoration(
          shape: BoxShape.circle,
          color: _primaryColor.withOpacity(0.08),
        ),
        child: Icon(Icons.timer, size: 18, color: _primaryColor),
      ),
      title: Text(
        'وقت التشغيل',
        style: TextStyle(
          fontFamily: 'Tajawal',
          fontSize: 12,
          color: _textColor.withOpacity(0.6),
        ),
      ),
      subtitle: Text(
        uptime,
        style: TextStyle(
          fontFamily: 'Tajawal',
          fontSize: 14,
          fontWeight: FontWeight.w600,
          color: _textColor,
        ),
      ),
      minLeadingWidth: 0,
      dense: true,
    );
  }

  Widget _buildActionButtons(Map<String, dynamic> user, bool isDisabled) {
    return Row(
      children: [
        Expanded(
          child: _buildActionButton(
            icon: isDisabled ? Icons.toggle_on : Icons.toggle_off,
            label: isDisabled ? 'تفعيل' : 'تعطيل',
            color: isDisabled ? Colors.green : Colors.red,
            onPressed: () => _toggleUserStatus(user),
          ),
        ),
        SizedBox(width: 8),
        Expanded(
          child: _buildActionButton(
            icon: Icons.delete_outline,
            label: 'حذف',
            color: _accentColor,
            onPressed: () => _confirmDeleteUser(user),
          ),
        ),
      ],
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return OutlinedButton(
      onPressed: onPressed,
      style: OutlinedButton.styleFrom(
        foregroundColor: color,
        side: BorderSide(color: color.withOpacity(0.3)),
        padding: EdgeInsets.symmetric(vertical: 10),
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
        backgroundColor: color.withOpacity(0.05),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: 18),
          SizedBox(width: 6),
          Text(label, style: TextStyle(fontFamily: 'Tajawal', fontSize: 12)),
        ],
      ),
    );
  }

  // دالة مساعدة لأزرار الإجراءات الأصغر
  Widget _buildSmallActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        onTap: onPressed,
        borderRadius: BorderRadius.circular(6),
        child: Padding(
          padding: EdgeInsets.symmetric(vertical: 6), // تقليل الحشو الرأسي
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(
                icon,
                size: 18, // تقليل حجم الأيقونة من 20 إلى 18
                color: color,
              ),
              SizedBox(height: 2), // تقليل المسافة
              Text(
                label,
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  fontSize: 10, // تقليل حجم الخط من 12 إلى 10
                  color: color,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // دالة مساعدة لعرض إحصائيات البيانات بشكل مضغوط
  Widget _buildCompactDataStat({
    required IconData icon,
    required String value,
    required Color color,
    required String label,
  }) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Icon(
          icon,
          size: 16, // تقليل حجم الأيقونة من 18 إلى 16
          color: color.withOpacity(0.9),
        ),
        SizedBox(height: 2), // تقليل المسافة
        Text(
          value,
          style: TextStyle(
            fontFamily: 'Tajawal',
            fontSize: 10, // تقليل حجم الخط من 12 إلى 10
            fontWeight: FontWeight.w500,
            color: _textColor.withOpacity(0.8),
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontFamily: 'Tajawal',
            fontSize: 9, // تقليل حجم الخط من 10 إلى 9
            color: _textColor.withOpacity(0.6),
          ),
        ),
      ],
    );
  }

  // دالة مساعدة لعرض إحصائيات البيانات
  Widget _buildDataStat({
    required IconData icon,
    required String value,
    required Color color,
    required String label,
  }) {
    return Column(
      children: [
        Icon(icon, size: 20, color: color),
        SizedBox(height: 6),
        Text(
          value,
          style: TextStyle(
            fontFamily: 'Tajawal',
            fontSize: 13,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(
            fontFamily: 'Tajawal',
            fontSize: 10,
            color: _textColor.withOpacity(0.6),
          ),
        ),
      ],
    );
  }

  // دالة مساعدة لحساب نسبة الاستخدام
  double _calculateUsagePercentage(Map<String, dynamic> user) {
    final bytesIn = int.tryParse(user['bytes-in']?.toString() ?? '0') ?? 0;
    final bytesOut = int.tryParse(user['bytes-out']?.toString() ?? '0') ?? 0;
    final limit =
        int.tryParse(user['limit-bytes-total']?.toString() ?? '1') ?? 1;

    final totalUsed = bytesIn + bytesOut;
    final validLimit = limit <= 0 ? 1 : limit;

    return (totalUsed / validLimit).clamp(0.0, 1.0);
  }

  // دالة مساعدة لإدارة اختيار المستخدم
  void _handleUserSelection(Map<String, dynamic> user, bool? value) {
    setState(() {
      if (value == true) {
        _selectedUsers.add(user['.id']);
      } else {
        _selectedUsers.remove(user['.id']);
      }
    });
  }

  Widget _buildPaginationControls() {
    final totalPages = (_totalItems / _itemsPerPage).ceil();
    final progressPercent = (_currentPage / totalPages * 100).round();

    return Column(
      children: [
        // شريط التقدم مع النسبة المئوية
        Container(
          padding: EdgeInsets.symmetric(horizontal: 20),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    "التقدم",
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: _textColor.withOpacity(0.7),
                      fontSize: 12,
                    ),
                  ),
                  Text(
                    "$progressPercent%",
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: _primaryColor,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 6),
              ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: LinearProgressIndicator(
                  value: _currentPage / totalPages,
                  backgroundColor: Colors.grey[200],
                  valueColor: AlwaysStoppedAnimation<Color>(
                    _primaryColor.withOpacity(0.8),
                  ),
                  minHeight: 8,
                ),
              ),
            ],
          ),
        ),

        SizedBox(height: 16),

        // أزرار التنقل مع تأثيرات خاصة
        Container(
          padding: EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              // زر السابق
              _buildPaginationButton(
                icon: Icons.arrow_back_ios_new_rounded,
                label: "السابق",
                isActive: _currentPage > 1,
                isNext: false,
                onPressed: () => _loadUsers(page: _currentPage - 1),
              ),

              // مؤشر الصفحات
              Container(
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                decoration: BoxDecoration(
                  color: _primaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(
                    color: _primaryColor.withOpacity(0.3),
                    width: 1.5,
                  ),
                ),
                child: RichText(
                  text: TextSpan(
                    children: [
                      TextSpan(
                        text: "$_currentPage",
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _primaryColor,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      TextSpan(
                        text: " / $totalPages",
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.7),
                          fontSize: 14,
                        ),
                      ),
                    ],
                  ),
                ),
              ),

              // زر التالي
              _buildPaginationButton(
                icon: Icons.arrow_forward_ios_rounded,
                label: "التالي",
                isActive: _currentPage < totalPages,
                isNext: true,
                onPressed: () => _loadUsers(page: _currentPage + 1),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // دالة مساعدة لإنشاء أزرار متسقة
  Widget _buildPaginationButton({
    required IconData icon,
    required String label,
    required bool isActive,
    required bool isNext,
    required VoidCallback onPressed,
  }) {
    return AnimatedContainer(
      duration: Duration(milliseconds: 300),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        boxShadow:
            isActive
                ? [
                  BoxShadow(
                    color: _primaryColor.withOpacity(0.2),
                    blurRadius: 8,
                    offset: Offset(0, 3),
                  ),
                ]
                : [],
      ),
      child: Material(
        color: isActive ? _primaryColor : Colors.grey[300],
        borderRadius: BorderRadius.circular(12),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: isActive ? onPressed : null,
          splashColor: Colors.white.withOpacity(0.2),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children:
                  isNext
                      ? [
                        Text(
                          label,
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: isActive ? Colors.white : Colors.grey[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        SizedBox(width: 8),
                        Icon(
                          icon,
                          size: 16,
                          color: isActive ? Colors.white : Colors.grey[600],
                        ),
                      ]
                      : [
                        Icon(
                          icon,
                          size: 16,
                          color: isActive ? Colors.white : Colors.grey[600],
                        ),
                        SizedBox(width: 8),
                        Text(
                          label,
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: isActive ? Colors.white : Colors.grey[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
            ),
          ),
        ),
      ),
    );
  }

  Widget build(BuildContext context) {
    final isMobile = MediaQuery.of(context).size.width < 768;

    return Directionality(
      textDirection: TextDirection.rtl,
      child: isMobile ? _buildMobileLayout() : _buildDesktopLayout(),
    );
  }

  Widget _buildDesktopLayout() {
    return Scaffold(
      backgroundColor: _backgroundColor,
      body: Row(
        children: [
          Container(
            width: 280,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.05),
              border: Border(
                right: BorderSide(color: Colors.white.withOpacity(0.1)),
              ),
            ),
            child: SingleChildScrollView(
              child: Column(
                children: [
                  const SizedBox(height: 40),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      children: [
                        Icon(Icons.people_alt, color: _primaryColor, size: 28),
                        const SizedBox(width: 10),
                        Text(
                          'إدارة المستخدمين',
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 30),
                  _buildDesktopNavigation(),
                ],
              ),
            ),
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    _backgroundColor.withOpacity(0.9),
                    _backgroundColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: Column(
                children: [
                  Container(
                    height: 60,
                    color: Colors.white.withOpacity(0.05),
                    child: Row(
                      children: [
                        IconButton(
                          icon: Icon(Icons.menu, color: _textColor),
                          onPressed: () {},
                        ),
                        Expanded(
                          child: Text(
                            'إدارة مستخدمي اليوزر مانجر',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                              fontSize: 20,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                        if (_selectedUsers.isNotEmpty)
                          AnimatedSwitcher(
                            duration: Duration(milliseconds: 300),
                            child: Container(
                              key: ValueKey<int>(_selectedUsers.length),
                              margin: EdgeInsets.symmetric(horizontal: 8),
                              padding: EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: _secondaryColor.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(20),
                                border: Border.all(
                                  color: _secondaryColor.withOpacity(0.3),
                                ),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.check_circle_rounded,
                                    size: 18,
                                    color: _secondaryColor,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    '${_selectedUsers.length}',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      fontSize: 14,
                                      fontWeight: FontWeight.bold,
                                      color: _secondaryColor,
                                    ),
                                  ),
                                  SizedBox(width: 6),
                                  InkWell(
                                    borderRadius: BorderRadius.circular(12),
                                    onTap:
                                        () => setState(
                                          () => _selectedUsers.clear(),
                                        ),
                                    child: Padding(
                                      padding: EdgeInsets.all(4),
                                      child: Icon(
                                        Icons.close,
                                        size: 16,
                                        color: _secondaryColor.withOpacity(0.7),
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        if (!_isLoading && !_searchingAllData) ...[
                          Tooltip(
                            message:
                                _selectedUsers.length ==
                                            _filteredUsers.length &&
                                        _selectedUsers.isNotEmpty
                                    ? 'إلغاء تحديد الكل'
                                    : 'تحديد الكل',
                            child: AnimatedContainer(
                              duration: Duration(milliseconds: 300),
                              margin: EdgeInsets.symmetric(horizontal: 4),
                              decoration: BoxDecoration(
                                color:
                                    _selectedUsers.length ==
                                                _filteredUsers.length &&
                                            _selectedUsers.isNotEmpty
                                        ? _primaryColor.withOpacity(0.2)
                                        : Colors.transparent,
                                borderRadius: BorderRadius.circular(8),
                                border: Border.all(
                                  color:
                                      _selectedUsers.length ==
                                                  _filteredUsers.length &&
                                              _selectedUsers.isNotEmpty
                                          ? _primaryColor
                                          : _borderColor,
                                  width: 1.5,
                                ),
                              ),
                              child: IconButton(
                                icon: Icon(
                                  _selectedUsers.length ==
                                              _filteredUsers.length &&
                                          _selectedUsers.isNotEmpty
                                      ? Icons.check_circle_rounded
                                      : Icons.check_circle_outline_rounded,
                                  size: 22,
                                  color:
                                      _selectedUsers.length ==
                                                  _filteredUsers.length &&
                                              _selectedUsers.isNotEmpty
                                          ? _primaryColor
                                          : _textColor.withOpacity(0.7),
                                ),
                                onPressed: () {
                                  setState(() {
                                    if (_selectedUsers.length ==
                                        _filteredUsers.length) {
                                      _selectedUsers.clear();
                                    } else {
                                      _selectedUsers =
                                          _filteredUsers
                                              .map(
                                                (user) => user['.id'] as String,
                                              )
                                              .toList();
                                    }
                                  });
                                  HapticFeedback.lightImpact();
                                },
                                splashColor: _primaryColor.withOpacity(0.1),
                                highlightColor: _primaryColor.withOpacity(0.05),
                              ),
                            ),
                          ),

                          _AppBarActionButton(
                            icon: Icons.person_remove_alt_1_rounded,
                            label: 'حذف',
                            onPressed: _deleteSelectedUsers,
                            color: _accentColor,
                          ),
                          _AppBarActionButton(
                            icon: Icons.delete_sweep,
                            label: 'تنظيف',
                            onPressed: _deleteExpiredUsers,
                            color: Colors.orange,
                          ),
                        ],
                      ],
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.all(16.0),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _buildUserCountBanner(),
                          SizedBox(height: 1),
                          Row(
                            children: [
                              Expanded(
                                child: SizedBox(
                                  height: 48,
                                  child: _buildSearchBar(),
                                ),
                              ),
                              SizedBox(width: 8),
                              SizedBox(
                                height: 48,
                                child: _buildItemsPerPageControl(),
                              ),
                            ],
                          ),
                          SizedBox(height: 16),
                          Expanded(
                            child: Card(
                              elevation: 0,
                              color: _backgroundColor,
                              child:
                                  _isLoading || _searchingAllData
                                      ? _buildLoadingIndicator()
                                      : _filteredUsers.isEmpty
                                      ? _buildEmptyState()
                                      : Column(
                                        children: [
                                          Expanded(child: _buildDesktopTable()),
                                          if (!_searchingAllData)
                                            _buildPaginationControls(),
                                        ],
                                      ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildMobileLayout() {
    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();

    return Scaffold(
      backgroundColor: _backgroundColor,
      key: _scaffoldKey,
      drawer: Drawer(child: _buildUniversalDrawer()),
      appBar: AppBar(
        backgroundColor: _backgroundColor,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.menu,
            color: _textColor,
          ), // هنا تحديد الأيقونة ولونها
          onPressed: () {
            _scaffoldKey.currentState?.openDrawer();
          },
        ),
        title: Text(
          'مستخدمي اليوزر مانجر',
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: _textColor,
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        centerTitle: true,
        actions: [
          if (_selectedUsers.isNotEmpty)
            AnimatedSwitcher(
              duration: Duration(milliseconds: 300),
              child: Container(
                key: ValueKey<int>(_selectedUsers.length),
                margin: EdgeInsets.symmetric(horizontal: 8),
                padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: _secondaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: _secondaryColor.withOpacity(0.3)),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.check_circle_rounded,
                      size: 18,
                      color: _secondaryColor,
                    ),
                    SizedBox(width: 6),
                    Text(
                      '${_selectedUsers.length}',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: _secondaryColor,
                      ),
                    ),
                    SizedBox(width: 6),
                    InkWell(
                      borderRadius: BorderRadius.circular(12),
                      onTap: () => setState(() => _selectedUsers.clear()),
                      child: Padding(
                        padding: EdgeInsets.all(4),
                        child: Icon(
                          Icons.close,
                          size: 16,
                          color: _secondaryColor.withOpacity(0.7),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
      ),

      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildUserCountBanner(),
            SizedBox(height: 1),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: SizedBox(height: 48, child: _buildSearchButton()),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      child: SizedBox(
                        height: 48,
                        child: _buildItemsPerPageControl(),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            SizedBox(height: 16),
            Expanded(
              child: Card(
                elevation: 0,
                color: _backgroundColor,
                child:
                    _isLoading || _searchingAllData
                        ? _buildLoadingIndicator()
                        : _filteredUsers.isEmpty
                        ? _buildEmptyState()
                        : Column(
                          children: [
                            if (!_searchingAllData)
                              Container(
                                padding: EdgeInsets.symmetric(
                                  vertical: 8,
                                  horizontal: 12,
                                ),
                                margin: EdgeInsets.only(bottom: 12),
                                decoration: BoxDecoration(
                                  color: _cardColor,
                                  borderRadius: BorderRadius.circular(12),
                                  border: Border.all(color: _borderColor),
                                ),
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: [
                                    Tooltip(
                                      message:
                                          _selectedUsers.length ==
                                                      _filteredUsers.length &&
                                                  _selectedUsers.isNotEmpty
                                              ? 'إلغاء التحديد'
                                              : 'تحديد الكل',
                                      child: Material(
                                        color: Colors.transparent,
                                        child: InkWell(
                                          borderRadius: BorderRadius.circular(
                                            12,
                                          ),
                                          onTap: () {
                                            setState(() {
                                              if (_selectedUsers.length ==
                                                  _filteredUsers.length) {
                                                _selectedUsers.clear();
                                              } else {
                                                _selectedUsers =
                                                    _filteredUsers
                                                        .map(
                                                          (user) =>
                                                              user['.id']
                                                                  as String,
                                                        )
                                                        .toList();
                                              }
                                            });
                                            HapticFeedback.lightImpact();
                                          },
                                          child: Padding(
                                            padding: EdgeInsets.all(8),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              children: [
                                                AnimatedSwitcher(
                                                  duration: Duration(
                                                    milliseconds: 300,
                                                  ),
                                                  child: Icon(
                                                    _selectedUsers.length ==
                                                                _filteredUsers
                                                                    .length &&
                                                            _selectedUsers
                                                                .isNotEmpty
                                                        ? Icons
                                                            .check_circle_rounded
                                                        : Icons
                                                            .check_circle_outline_rounded,
                                                    key: ValueKey<bool>(
                                                      _selectedUsers.length ==
                                                          _filteredUsers.length,
                                                    ),
                                                    size: 22,
                                                    color:
                                                        _selectedUsers.length ==
                                                                    _filteredUsers
                                                                        .length &&
                                                                _selectedUsers
                                                                    .isNotEmpty
                                                            ? _primaryColor
                                                            : _textColor
                                                                .withOpacity(
                                                                  0.7,
                                                                ),
                                                  ),
                                                ),
                                                SizedBox(height: 4),
                                                Text(
                                                  'الكل',
                                                  style: TextStyle(
                                                    fontFamily: 'Tajawal',
                                                    fontSize: 12,
                                                    color:
                                                        _selectedUsers.length ==
                                                                    _filteredUsers
                                                                        .length &&
                                                                _selectedUsers
                                                                    .isNotEmpty
                                                            ? _primaryColor
                                                            : _textColor
                                                                .withOpacity(
                                                                  0.7,
                                                                ),
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      ),
                                    ),

                                    _SmallActionButton(
                                      icon: Icons.person_remove_alt_1_rounded,
                                      label: 'حذف',
                                      onPressed: _deleteSelectedUsers,
                                      color: _accentColor,
                                    ),
                                    _SmallActionButton(
                                      icon: Icons.delete_sweep,
                                      label: 'تنظيف',
                                      onPressed: _deleteExpiredUsers,
                                      color: Colors.orange,
                                    ),
                                  ],
                                ),
                              ),
                            Expanded(child: _buildMobileList()),
                            if (!_searchingAllData) _buildPaginationControls(),
                          ],
                        ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUniversalDrawer() {
    return Drawer(
      backgroundColor: _backgroundColor,
      child: SafeArea(
        child: SingleChildScrollView(
          child: Column(
            children: [
              // Stylish Drawer Header
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 25,
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      _primaryColor.withOpacity(0.9),
                      _primaryColor.withOpacity(0.6),
                    ],
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 6,
                      offset: Offset(0, 3),
                    ),
                  ],
                  borderRadius: BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                ),
                child: Row(
                  children: [
                    // Logo or Icon Container
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white.withOpacity(0.1),
                        border: Border.all(color: Colors.white24, width: 1),
                      ),
                      child: Icon(
                        Icons.network_check,
                        color: Colors.white,
                        size: 30,
                      ),
                    ),
                    const SizedBox(width: 16),
                    // App Title & Subtitle
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Micro Panel',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white,
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'لوحة تحكم الشبكة الذكية',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white70,
                              fontSize: 14,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

              // Main Navigation Items
              _buildUniversalDrawerItem(
                icon: Icons.dashboard,
                title: 'لوحة التحكم',
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    PageRouteBuilder(
                      pageBuilder:
                          (context, animation, secondaryAnimation) =>
                              RouterDetailsPage(client: widget.client),
                      transitionsBuilder: (
                        context,
                        animation,
                        secondaryAnimation,
                        child,
                      ) {
                        const begin = Offset(0.0, 1.0);
                        const end = Offset.zero;
                        const curve = Curves.ease;
                        var tween = Tween(
                          begin: begin,
                          end: end,
                        ).chain(CurveTween(curve: curve));
                        return SlideTransition(
                          position: animation.drive(tween),
                          child: child,
                        );
                      },
                      transitionDuration: const Duration(milliseconds: 300),
                    ),
                  );
                },
              ),

              // Hotspot Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة الهوتسبوت',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.people,
                    title: 'قائمة المستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UsersPage(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.speed,
                    title: 'البروفايل',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  HotspotProfile(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.person_add,
                    title: 'إضافة مستخدم',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddHotspotCardsPage(
                                    client: widget.client,
                                    initialTab: 0,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.group_add,
                    title: 'إضافة مستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddHotspotCardsPage(
                                    client: widget.client,
                                    initialTab: 1,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // User Manager Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(
                      Icons.manage_accounts,
                      color: Colors.white.withOpacity(0.7),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة اليوزر مانجر',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                initiallyExpanded: true,
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.people_outline,
                    title: 'قائمة المستخدمين',
                    isActive: true,
                    onTap: () {},
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.speed,
                    title: 'البروفايل',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerProfile(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.payment_rounded,
                    title: 'إضافة مستخدم',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddUserManagerCards(
                                    client: widget.client,
                                    initialTab: 0,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.credit_score,
                    title: 'إضافة مستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AddUserManagerCards(
                                    client: widget.client,
                                    initialTab: 1,
                                  ),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.assignment,
                    title: 'السجلات',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerSession(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // Settings Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'الإعدادات والأدوات',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.settings,
                    title: 'قبل الطباعة والأمان',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  FreeRebuildDB(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.backup,
                    title: 'النسخ الاحتياطي',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  backupSN(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // Help Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(Icons.help, color: Colors.white.withOpacity(0.7)),
                    const SizedBox(width: 12),
                    Text(
                      'المساعدة والدعم',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.help_outline,
                    title: 'مركز المساعدة',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  HelpDesk(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.feedback,
                    title: 'إرسال ملاحظات',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  SendNotes(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.info_outline,
                    title: 'حول التطبيق',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AboutApp(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                ],
              ),

              const Divider(color: Colors.white24),

              // Logout Item
              _buildUniversalDrawerItem(
                icon: Icons.logout,
                title: 'تسجيل خروج',
                color: Colors.red,
                onTap: () {
                  Navigator.pushReplacement(
                    context,
                    PageRouteBuilder(
                      pageBuilder:
                          (context, animation, secondaryAnimation) => Login(),
                      transitionsBuilder: (
                        context,
                        animation,
                        secondaryAnimation,
                        child,
                      ) {
                        const begin = Offset(0.0, 1.0);
                        const end = Offset.zero;
                        const curve = Curves.ease;
                        var tween = Tween(
                          begin: begin,
                          end: end,
                        ).chain(CurveTween(curve: curve));
                        return SlideTransition(
                          position: animation.drive(tween),
                          child: child,
                        );
                      },
                      transitionDuration: const Duration(milliseconds: 300),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUniversalDrawerItem({
    required IconData icon,
    required String title,
    Color color = Colors.white,
    required VoidCallback onTap,
    bool isActive = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      decoration: BoxDecoration(
        color: isActive ? _primaryColor.withOpacity(0.1) : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border:
            isActive
                ? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
                : null,
      ),
      child: ListTile(
        leading: Icon(icon, color: isActive ? _primaryColor : color),
        title: Text(
          title,
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: isActive ? _primaryColor : color,
            fontSize: 14,
            fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        onTap: onTap,
        contentPadding: const EdgeInsets.symmetric(horizontal: 16),
      ),
    );
  }

  Widget _buildDrawerItem({
    required IconData icon,
    required String title,
    Color color = Colors.white,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(title, style: TextStyle(fontFamily: 'Tajawal', color: color)),
      onTap: onTap,
    );
  }

  Widget _buildDesktopNavigation() {
    return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: MediaQuery.of(context).size.height,
      ),
      child: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            // قسم الإدارة الرئيسية
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Text(
                'الإدارة الرئيسية',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: Colors.white.withOpacity(0.5),
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            _buildNavItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              isActive: false,
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder:
                        (context) => RouterDetailsPage(client: widget.client),
                  ),
                );
              },
            ),

            // قسم الهوتسبوت  (قابل للطي)
            _buildExpandableSection(
              title: 'إدارة الهوتسبوت',
              icon: Icons.wifi,
              initiallyExpanded: isHotspotExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isHotspotExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (context) => UsersPage(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.speed,
                  title: 'البروفايل',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => HotspotProfile(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.person_add,
                  title: 'اضافة مستخدم',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddHotspotCardsPage(
                              client: widget.client,
                              initialTab: 0,
                            ),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.group_add,
                  title: 'اضافة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddHotspotCardsPage(
                              client: widget.client,
                              initialTab: 1,
                            ),
                      ),
                    );
                  },
                ),
              ],
            ),

            // قسم اليوزر مانجر (قابل للطي)
            _buildExpandableSection(
              title: 'إدارة اليوزر مانجر',
              icon: Icons.manage_accounts,
              initiallyExpanded: isUserManagerExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isUserManagerExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.people_outline,
                  title: 'قائمة المستخدمين  ',
                  isActive: true,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.speed,
                  title: 'البروفايل',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) =>
                                UserManagerProfile(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.payment_rounded,
                  title: 'اضافة مستخدم ',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (_) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 0,
                            ),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.credit_score,
                  title: 'اضافة المستخدمين ',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (_) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 1,
                            ),
                      ),
                    );
                  },
                ),

                _buildNavItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (_) => UserManagerSession(client: widget.client),
                      ),
                    );
                  },
                ),
              ],
            ),

            // قسم الإعدادات والأدوات (قابل للطي)
            _buildExpandableSection(
              title: 'الإعدادات والأدوات',
              icon: Icons.settings,
              initiallyExpanded: isSettingsExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isSettingsExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.settings,
                  title: 'قبل الطباعة والأمان',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => FreeRebuildDB(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => backupSN(client: widget.client),
                      ),
                    );
                  },
                ),
              ],
            ),

            // قسم المساعدة والدعم (قابل للطي)
            _buildExpandableSection(
              title: 'المساعدة والدعم',
              icon: Icons.help,
              initiallyExpanded: isHelpExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isHelpExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.help_outline,
                  title: 'مركز المساعدة',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => HelpDesk(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => SendNotes(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => AboutApp(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.logout,
                  title: 'تسجيل الخروج',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => Login()),
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildNavItem({
    required IconData icon,
    required String title,
    required bool isActive,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 4),
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: isActive ? _primaryColor.withOpacity(0.2) : Colors.transparent,
          borderRadius: BorderRadius.circular(8),
          border:
              isActive
                  ? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
                  : null,
        ),
        child: Row(
          children: [
            Icon(
              icon,
              color: isActive ? _primaryColor : Colors.white.withOpacity(0.7),
              size: 24,
            ),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: isActive ? Colors.white : Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
              ),
            ),
            if (isActive) const Spacer(),
            if (isActive)
              Container(
                width: 8,
                height: 8,
                decoration: BoxDecoration(
                  color: _primaryColor,
                  shape: BoxShape.circle,
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildExpandableSection({
    required String title,
    required IconData icon,
    required List<Widget> children,
    required bool initiallyExpanded,
    required ValueChanged<bool> onExpansionChanged,
  }) {
    return ExpansionTile(
      title: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            Icon(icon, color: Colors.white.withOpacity(0.7), size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
      childrenPadding: const EdgeInsets.only(left: 16),
      collapsedIconColor: Colors.white.withOpacity(0.7),
      iconColor: Colors.white.withOpacity(0.7),
      initiallyExpanded: initiallyExpanded,
      onExpansionChanged: onExpansionChanged,
      children: children,
    );
  }
}

class _Debouncer {
  final int milliseconds;
  Timer? _timer;
  _Debouncer({required this.milliseconds});
  void run(VoidCallback action) {
    _timer?.cancel();
    _timer = Timer(Duration(milliseconds: milliseconds), action);
  }

  void dispose() {
    _timer?.cancel();
  }
}

// Widget for reusable action buttons
class _ActionButton extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onPressed;
  final Color color;
  final bool isPrimary;

  const _ActionButton({
    required this.icon,
    required this.label,
    required this.onPressed,
    required this.color,
    this.isPrimary = false,
  });

  @override
  Widget build(BuildContext context) {
    final isSmallScreen = MediaQuery.of(context).size.width < 400;

    return Expanded(
      child: Material(
        borderRadius: BorderRadius.circular(12),
        color: isPrimary ? color : color.withOpacity(0.85),
        child: InkWell(
          borderRadius: BorderRadius.circular(12),
          onTap: onPressed,
          child: Container(
            padding: EdgeInsets.symmetric(
              vertical: isSmallScreen ? 10 : 12,
              horizontal: 4,
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(icon, size: isSmallScreen ? 18 : 20, color: Colors.white),
                if (!isSmallScreen) SizedBox(width: 4),
                if (!isSmallScreen)
                  Text(
                    label,
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white,
                      fontSize: isSmallScreen ? 12 : 14,
                    ),
                  ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

// أضف هذا الـ Widget في نفس الكلاس
class _SmallActionButton extends StatelessWidget {
  final IconData icon;
  final String label;
  final VoidCallback onPressed;
  final Color color;

  const _SmallActionButton({
    required this.icon,
    required this.label,
    required this.onPressed,
    required this.color,
  });

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: onPressed,
        child: Padding(
          padding: EdgeInsets.all(8),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Icon(icon, size: 20, color: color),
              SizedBox(height: 4),
              Text(
                label,
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  fontSize: 12,
                  color: color,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

ملاحظة اعطيني الجزء السابق والجزء المراد استبدالة بة