اريد بدلاً من استخدام هذة الطريقة 
Future<void> _deleteExpiredUsers() async {
    try {
      setState(() => _isLoading = true);

      // جلب جميع المستخدمين من الرواتر
      final allUsers = await widget.client.talk([
        '/tool/user-manager/user/print',
      ]);

      // تصفية المستخدمين الذين ليس لديهم بروفايل أو بروفايلهم فارغ
      final usersToDelete =
          allUsers
              .where(
                (user) =>
                    user['actual-profile'] == null ||
                    user['actual-profile'].toString().isEmpty ||
                    user['profile'] == null ||
                    user['profile'].toString().isEmpty,
              )
              .map((user) => user['.id'] as String)
              .toList();

      // حذف المستخدمين منتهي الصلاحية
      for (var userId in usersToDelete) {
        await widget.client.talk([
          '/tool/user-manager/user/remove',
          '=.id=$userId',
        ]);
      }

      // تحديث القائمة المحلية
      final users = await _loadUsersFromJson();
      final updatedUsers =
          users
              .where(
                (user) =>
                    (user['actual-profile'] != null &&
                        user['actual-profile'].toString().isNotEmpty) ||
                    (user['profile'] != null &&
                        user['profile'].toString().isNotEmpty),
              )
              .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),
          ),
        ),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }
اريد ان يتم حذف جميع المستخدمين الذين ليس لهم profile في الراوتر وبعد الانتها من الحذف في الراوتر اريد ان يتم تطبيق الحذف على الملف الذي يحتوي على المستخدمين للعلم الكود
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/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');
  }

  Future<void> _editUserProfile(Map<String, dynamic> user) async {
    final routerVersion = await _getRouterVersion();

    if (routerVersion < 7) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'هذه الميزة متاحة فقط لإصدار 7 فما فوق، سيتم توفيرها قريباً لإصدار 6',
          ),
          backgroundColor: _warningColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
      return;
    }

    final currentProfile = user['actual-profile'] ?? user['profile'] ?? '';
    String? selectedProfile = currentProfile;

    // جلب قائمة البروفايلات من الرواتر
    try {
      setState(() => _isLoading = true);
      final profiles = await widget.client.talk([
        '/user-manager/profile/print',
      ]);
      final profileNames = profiles.map((p) => p['name'] as String).toList();

      await showDialog(
        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: _primaryColor),
                ),
                content: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text('اسم المستخدم: ${user['username']}'),
                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 12),
                      decoration: BoxDecoration(
                        color: _cardColor,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: _borderColor),
                      ),
                      child: DropdownButton<String>(
                        dropdownColor: _surfaceColor,
                        isExpanded: true,
                        value: selectedProfile,
                        items:
                            profileNames.map((profile) {
                              return DropdownMenuItem<String>(
                                value: profile,
                                child: Text(
                                  profile,
                                  style: TextStyle(
                                    fontFamily: 'Tajawal',
                                    color: _textColor,
                                  ),
                                ),
                              );
                            }).toList(),
                        onChanged: (value) {
                          selectedProfile = value;
                        },
                        hint: Text(
                          'اختر البروفايل',
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.7),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.pop(context),
                    child: Text(
                      'إلغاء',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: _textColor,
                      ),
                    ),
                  ),
                  ElevatedButton(
                    onPressed: () async {
                      if (selectedProfile == null ||
                          selectedProfile == currentProfile) {
                        Navigator.pop(context);
                        return;
                      }

                      try {
                        Navigator.pop(context);
                        setState(() => _isLoading = true);

                        // إزالة المستخدم من البروفايل الحالي
                        await widget.client.talk([
                          '/user-manager/user-profile/remove',
                          '=[find user=${user['.id']} profile=$currentProfile]',
                        ]);

                        // إضافة المستخدم إلى البروفايل الجديد
                        await widget.client.talk([
                          '/user-manager/user-profile/add',
                          '=user=${user['.id']}',
                          '=profile=$selectedProfile',
                        ]);

                        // تحديث البيانات المحلية
                        final users = await _loadUsersFromJson();
                        final updatedUsers =
                            users.map((u) {
                              if (u['.id'] == user['.id']) {
                                return {
                                  ...u,
                                  'actual-profile': selectedProfile,
                                };
                              }
                              return u;
                            }).toList();
                        await _saveUsersToJson(updatedUsers);

                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('تم تعديل بروفايل المستخدم بنجاح'),
                            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),
                            ),
                          ),
                        );
                      } finally {
                        setState(() => _isLoading = false);
                      }
                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: _primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(12),
                      ),
                    ),
                    child: Text('حفظ'),
                  ),
                ],
              ),
            ),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('فشل في جلب قائمة البروفايلات'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    } finally {
      setState(() => _isLoading = false);
    }
  }

  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: 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('بحث'),
              ),
            ],
          ),
        );
      },
    );
  }

  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('حذف'),
                ),
              ],
            ),
          ),
    );

    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',
          ]);
        }

        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(() => _selectedUsers.clear());
        _loadUsers(page: _currentPage);
      } 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 {
    try {
      setState(() => _isLoading = true);

      // جلب جميع المستخدمين من الرواتر
      final allUsers = await widget.client.talk([
        '/tool/user-manager/user/print',
      ]);

      // تصفية المستخدمين الذين ليس لديهم بروفايل أو بروفايلهم فارغ
      final usersToDelete =
          allUsers
              .where(
                (user) =>
                    user['actual-profile'] == null ||
                    user['actual-profile'].toString().isEmpty ||
                    user['profile'] == null ||
                    user['profile'].toString().isEmpty,
              )
              .map((user) => user['.id'] as String)
              .toList();

      // حذف المستخدمين منتهي الصلاحية
      for (var userId in usersToDelete) {
        await widget.client.talk([
          '/tool/user-manager/user/remove',
          '=.id=$userId',
        ]);
      }

      // تحديث القائمة المحلية
      final users = await _loadUsersFromJson();
      final updatedUsers =
          users
              .where(
                (user) =>
                    (user['actual-profile'] != null &&
                        user['actual-profile'].toString().isNotEmpty) ||
                    (user['profile'] != null &&
                        user['profile'].toString().isNotEmpty),
              )
              .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),
          ),
        ),
      );
    } 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 currentStatus = user['disabled'] == 'true';
    final newStatus = currentStatus ? 'false' : 'true';
    try {
      await widget.client.talk([
        '/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),
          ),
        ),
      );
    }
  }

  Future<void> _confirmDeleteUser(Map<String, dynamic> user) async {
    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([
                        '/tool/user-manager/user/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),
                          ),
                        ),
                      );

                      _loadUsers(page: _currentPage);
                    } 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('حذف'),
                ),
              ],
            ),
          ),
    );
  }

  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('الحالة'),
                          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';

                            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:
                                          (user['actual-profile'] == null ||
                                                  (user['actual-profile'] ??
                                                          user['profile'])!
                                                      .toString()
                                                      .isEmpty)
                                              ? Colors.red.withOpacity(0.1)
                                              : _secondaryColor.withOpacity(
                                                0.1,
                                              ),
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(
                                        color:
                                            (user['actual-profile'] == null ||
                                                    (user['actual-profile'] ??
                                                            user['profile'])!
                                                        .toString()
                                                        .isEmpty)
                                                ? Colors.red.withOpacity(0.3)
                                                : _secondaryColor.withOpacity(
                                                  0.3,
                                                ),
                                      ),
                                    ),
                                    child: Text(
                                      (user['actual-profile'] == null ||
                                              (user['actual-profile'] ??
                                                      user['profile'])!
                                                  .toString()
                                                  .isEmpty)
                                          ? 'منتهي'
                                          : (user['actual-profile'] ??
                                                      user['profile'])
                                                  ?.toString() ??
                                              'غير معروف',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color:
                                            (user['actual-profile'] == null ||
                                                    (user['actual-profile'] ??
                                                            user['profile'])!
                                                        .toString()
                                                        .isEmpty)
                                                ? Colors.red
                                                : _secondaryColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 80),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          isDisabled
                                              ? Colors.red.withOpacity(0.1)
                                              : _successColor.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(
                                        color:
                                            isDisabled
                                                ? Colors.red.withOpacity(0.3)
                                                : _successColor.withOpacity(
                                                  0.3,
                                                ),
                                      ),
                                    ),
                                    child: Text(
                                      isDisabled ? 'معطل' : 'نشط',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color:
                                            isDisabled
                                                ? Colors.red
                                                : _successColor,
                                      ),
                                    ),
                                  ),
                                ),
                                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(
                                      user['last-seen'] != null
                                          ? user['last-seen'] == 'never'
                                              ? 'جديد'
                                              : user['last-seen'].toString() ??
                                                  'لم يظهر'
                                          : user['state'] == 'waiting'
                                          ? 'جديد'
                                          : 'مستخدم',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 180),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Tooltip(
                                          message: 'تعديل البروفايل',
                                          child: InkWell(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                            onTap: () => _editUserProfile(user),
                                            child: Container(
                                              padding: EdgeInsets.all(6),
                                              decoration: BoxDecoration(
                                                color: _primaryColor
                                                    .withOpacity(0.1),
                                                borderRadius:
                                                    BorderRadius.circular(20),
                                              ),
                                              child: Icon(
                                                Icons.edit,
                                                size: 20,
                                                color: _primaryColor,
                                              ),
                                            ),
                                          ),
                                        ),
                                        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';
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      alignment: Alignment.center, // <-- هذا السطر يضمن التوسيط
      decoration: BoxDecoration(
        color:
            (user['actual-profile'] == null ||
                    (user['actual-profile'] ?? user['profile'])!
                        .toString()
                        .isEmpty)
                ? Colors.red.withOpacity(0.1)
                : (isDisabled
                    ? Colors.grey.withOpacity(0.1)
                    : _secondaryColor.withOpacity(0.1)),
        borderRadius: BorderRadius.circular(6),
        border: Border.all(
          color:
              (user['actual-profile'] == null ||
                      (user['actual-profile'] ?? user['profile'])!
                          .toString()
                          .isEmpty)
                  ? Colors.red.withOpacity(0.3)
                  : (isDisabled
                      ? Colors.grey.withOpacity(0.3)
                      : _secondaryColor.withOpacity(0.3)),
        ),
      ),
      child: Text(
        (user['actual-profile'] == null ||
                (user['actual-profile'] ?? user['profile'])!.toString().isEmpty)
            ? 'منتهي'
            : (user['actual-profile'] ?? user['profile'])?.toString() ??
                'غير معروف',
        style: TextStyle(
          fontFamily: 'Tajawal',
          fontSize: 12,
          fontWeight: FontWeight.w500,
          color:
              (user['actual-profile'] == null ||
                      (user['actual-profile'] ?? user['profile'])!
                          .toString()
                          .isEmpty)
                  ? Colors.red
                  : (isDisabled ? Colors.grey : _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: Icons.edit_outlined,
            label: 'تعديل',
            color: _warningColor,
            onPressed: () => _editUserProfile(user),
          ),
        ),
        SizedBox(width: 8),
        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: ListView(
          padding: EdgeInsets.zero,
          children: [
            SizedBox(
              height: 70,
              child: DrawerHeader(
                decoration: BoxDecoration(
                  color: _primaryColor.withOpacity(0.1),
                  border: Border(
                    bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.network_check,
                          size: 30,
                          color: Colors.white,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Micro Panel',
                          style: const TextStyle(
                            fontFamily: 'Tajawal',
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            // 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: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerUserList(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) =>
                                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: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.security,
                  title: 'الأمان',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.cloud,
                  title: 'التحديثات',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),

            // 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,
  }) {
    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(
        title,
        style: TextStyle(fontFamily: 'Tajawal', color: color, fontSize: 14),
      ),
      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: () {},
                ),
                _buildNavItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.security,
                  title: 'الأمان',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.cloud,
                  title: 'التحديثات',
                  isActive: false,
                  onTap: () {},
                ),
              ],
            ),

            // قسم المساعدة والدعم (قابل للطي)
            _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,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}


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