لماذا لا يظهر الشريط الجانبي في الواجهه
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.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 UsersPage extends StatefulWidget {
  final RouterOSClient client;
  const UsersPage({Key? key, required this.client}) : super(key: key);
  @override
  _UsersPageState createState() => _UsersPageState();
}

class _UsersPageState extends State<UsersPage> {
  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);

  Future<File> _getJsonFile() async {
    final directory = await getApplicationDocumentsDirectory();
    final filePath = path.join(directory.path, 'hotspot_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),
          ),
        ),
      ),
    );
  }

  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(
              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(color: _primaryColor),
            ),
            content: _buildSearchBar(), // نستخدم نفس شريط البحث الحالي
            actions: [
              TextButton(
                onPressed: () {
                  Navigator.pop(context);
                  _searchController.clear();
                },
                child: Text('إلغاء', style: TextStyle(color: _textColor)),
              ),
              ElevatedButton(
                onPressed: () => Navigator.pop(context),
                style: ElevatedButton.styleFrom(
                  backgroundColor: _primaryColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(12),
                  ),
                ),
                child: Text('بحث'),
              ),
            ],
          ),
        );
      },
    );
  }

  Future<void> _showAddBytesDialog() async {
    _addBytesController.clear();
    _addBytesUnit = 'MB';

    final result = await showDialog<bool>(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder: (context, setState) {
              return Directionality(
                textDirection: TextDirection.rtl,
                child: AlertDialog(
                  backgroundColor: _surfaceColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  title: Text(
                    'إضافة رصيد إضافي',
                    style: TextStyle(color: _primaryColor),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextFormField(
                        controller: _addBytesController,
                        decoration: InputDecoration(
                          labelText: 'كمية البيانات المضافة',
                          labelStyle: TextStyle(
                            color: _textColor.withOpacity(0.7),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          filled: true,
                          fillColor: _cardColor,
                          prefixIcon: Icon(Icons.add, color: _primaryColor),
                          suffix: DropdownButton<String>(
                            dropdownColor: _surfaceColor,
                            value: _addBytesUnit,
                            items:
                                ['MB', 'GB'].map((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(
                                      value,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _addBytesUnit = newValue);
                              }
                            },
                          ),
                        ),
                        keyboardType: TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(color: _textColor),
                      ),
                      SizedBox(height: 16),
                      Text(
                        'سيتم إضافة هذه الكمية إلى الرصيد الحالي للمستخدمين المحددين',
                        style: TextStyle(color: _textColor.withOpacity(0.5)),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text('إلغاء', style: TextStyle(color: _textColor)),
                    ),
                    ElevatedButton(
                      onPressed: () => Navigator.pop(context, true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text('إضافة'),
                    ),
                  ],
                ),
              );
            },
          ),
    );

    if (result == true && _addBytesController.text.isNotEmpty) {
      try {
        final inputValue = double.tryParse(_addBytesController.text) ?? 0;
        int bytesToAdd;

        switch (_addBytesUnit) {
          case 'MB':
            bytesToAdd = (inputValue * 1024 * 1024).round();
            break;
          case 'GB':
            bytesToAdd = (inputValue * 1024 * 1024 * 1024).round();
            break;
          default:
            bytesToAdd = (inputValue * 1024 * 1024).round();
        }

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

        setState(() => _isLoading = true);

        for (var userId in _selectedUsers) {
          final user = _users.firstWhere((u) => u['.id'] == userId);
          final currentBytes =
              int.tryParse(user['limit-bytes-total']?.toString() ?? '0') ?? 0;
          final newBytes = currentBytes + bytesToAdd;

          await widget.client.talk([
            '/ip/hotspot/user/set',
            '=.id=$userId',
            '=limit-bytes-total=$newBytes',
          ]);
        }

        final users = await _loadUsersFromJson();
        final updatedUsers =
            users.map((u) {
              if (_selectedUsers.contains(u['.id'])) {
                final currentBytes =
                    int.tryParse(u['limit-bytes-total']?.toString() ?? '0') ??
                    0;
                return {
                  ...u,
                  'limit-bytes-total': (currentBytes + bytesToAdd).toString(),
                };
              }
              return u;
            }).toList();

        await _saveUsersToJson(updatedUsers);

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم إضافة الرصيد لـ ${_selectedUsers.length} مستخدم'),
            backgroundColor: _successColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );

        _loadUsers(page: _currentPage);
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('خطأ في إضافة الرصيد: $e'),
            backgroundColor: _accentColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      } finally {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _showEditSelectedUsersDialog() async {
    _limitBytesController.clear();
    _selectedUnit = 'MB';
    final result = await showDialog<bool>(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder: (context, setState) {
              return Directionality(
                textDirection: TextDirection.rtl,
                child: AlertDialog(
                  backgroundColor: _surfaceColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  title: Text(
                    'تعديل الرصيد الحالي',
                    style: TextStyle(color: _primaryColor),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextFormField(
                        controller: _limitBytesController,
                        decoration: InputDecoration(
                          labelText: 'الحد الأقصى للبيانات',
                          labelStyle: TextStyle(
                            color: _textColor.withOpacity(0.7),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          filled: true,
                          fillColor: _cardColor,
                          prefixIcon: Icon(
                            Icons.data_usage,
                            color: _primaryColor,
                          ),
                          suffix: DropdownButton<String>(
                            dropdownColor: _surfaceColor,
                            value: _selectedUnit,
                            items:
                                ['MB', 'GB'].map((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(
                                      value,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _selectedUnit = newValue);
                              }
                            },
                          ),
                        ),
                        keyboardType: TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(color: _textColor),
                      ),
                      SizedBox(height: 16),
                      Text(
                        'سيتم تعيين هذا الرصيد للمستخدمين المحددين (${_selectedUsers.length})',
                        style: TextStyle(color: _textColor.withOpacity(0.5)),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text('إلغاء', style: TextStyle(color: _textColor)),
                    ),
                    ElevatedButton(
                      onPressed: () => Navigator.pop(context, true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text('حفظ'),
                    ),
                  ],
                ),
              );
            },
          ),
    );

    if (result == true && _limitBytesController.text.isNotEmpty) {
      try {
        final inputValue = double.tryParse(_limitBytesController.text) ?? 0;
        int bytes;
        switch (_selectedUnit) {
          case 'MB':
            bytes = (inputValue * 1024 * 1024).round();
            break;
          case 'GB':
            bytes = (inputValue * 1024 * 1024 * 1024).round();
            break;
          default:
            bytes = (inputValue * 1024 * 1024).round();
        }

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

        setState(() => _isLoading = true);

        for (var userId in _selectedUsers) {
          await widget.client.talk([
            '/ip/hotspot/user/set',
            '=.id=$userId',
            '=limit-bytes-total=$bytes',
          ]);
        }

        final users = await _loadUsersFromJson();
        final updatedUsers =
            users.map((u) {
              if (_selectedUsers.contains(u['.id'])) {
                return {...u, 'limit-bytes-total': bytes.toString()};
              }
              return u;
            }).toList();

        await _saveUsersToJson(updatedUsers);

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم تعديل الرصيد لـ ${_selectedUsers.length} مستخدم'),
            backgroundColor: _successColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );

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

  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(color: _accentColor)),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف ${_selectedUsers.length} مستخدم؟',
                style: TextStyle(color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text('إلغاء', style: TextStyle(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 {
        setState(() => _isLoading = true);
        for (var userId in _selectedUsers) {
          await widget.client.talk(['/ip/hotspot/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('خطأ في الحذف: $e'),
            backgroundColor: _accentColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      } finally {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<void> _deleteExpiredUsers() async {
    try {
      setState(() => _isLoading = true);
      final users = await _loadUsersFromJson();
      final expiredUsers =
          users.where((user) {
            final limitBytes =
                int.tryParse(user['limit-bytes-total']?.toString() ?? '0') ?? 0;
            if (limitBytes == 0) return false;
            final bytesIn =
                int.tryParse(user['bytes-in']?.toString() ?? '0') ?? 0;
            final bytesOut =
                int.tryParse(user['bytes-out']?.toString() ?? '0') ?? 0;
            final totalUsed = bytesIn + bytesOut;
            return totalUsed >= limitBytes;
          }).toList();

      for (var user in expiredUsers) {
        await widget.client.talk([
          '/ip/hotspot/user/remove',
          '=.id=${user['.id']}',
        ]);
      }

      final updatedUsers =
          users
              .where(
                (user) => !expiredUsers.any((u) => u['.id'] == user['.id']),
              )
              .toList();
      await _saveUsersToJson(updatedUsers);

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

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

  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 {
    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.where((user) {
        final hasId = user['.id'] != null && user['.id'].toString().isNotEmpty;
        final hasName =
            user['name'] != null && user['name'].toString().isNotEmpty;
        return hasId && hasName;
      }).toList();
    } catch (e) {
      return [];
    }
  }

  @override
  void initState() {
    super.initState();
    _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['name']?.toString().toLowerCase() ?? '';
            final profile = user['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('خطأ في البحث: $e'),
          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('خطأ في جلب البيانات: $e'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    }
  }

  String _formatBytes(dynamic bytes) {
    int value = 0;
    if (bytes is int) {
      value = bytes;
    } else if (bytes is String) {
      value = int.tryParse(bytes) ?? 0;
    }
    if (value < 1024) return '$value بايت';
    if (value < 1024 * 1024)
      return '${(value / 1024).toStringAsFixed(1)} كيلوبايت';
    if (value < 1024 * 1024 * 1024)
      return '${(value / (1024 * 1024)).toStringAsFixed(1)} ميجابايت';
    return '${(value / (1024 * 1024 * 1024)).toStringAsFixed(1)} جيجابايت';
  }

  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([
        '/ip/hotspot/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['name']} تم ${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('خطأ في تعديل الحالة: $e'),
          backgroundColor: _accentColor,
          behavior: SnackBarBehavior.floating,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
        ),
      );
    }
  }

  Future<void> _showEditLimitBytesDialog(Map<String, dynamic> user) async {
    final currentBytes =
        int.tryParse(user['limit-bytes-total']?.toString() ?? '0') ?? 0;
    _selectedUnit = 'MB';
    double currentValue = currentBytes / (1024 * 1024);
    if (currentValue == currentValue.roundToDouble()) {
      _limitBytesController.text = currentValue.round().toString();
    } else {
      _limitBytesController.text = currentValue.toStringAsFixed(1);
    }

    final result = await showDialog<bool>(
      context: context,
      builder:
          (context) => StatefulBuilder(
            builder: (context, setState) {
              return Directionality(
                textDirection: TextDirection.rtl,
                child: AlertDialog(
                  backgroundColor: _surfaceColor,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(16),
                  ),
                  title: Text(
                    'تعديل الحد الأقصى للبيانات',
                    style: TextStyle(color: _primaryColor),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'اسم المستخدم: ${user['name']}',
                        style: TextStyle(color: _textColor),
                      ),
                      SizedBox(height: 16),
                      TextFormField(
                        controller: _limitBytesController,
                        decoration: InputDecoration(
                          labelText: 'الحد الأقصى للبيانات',
                          labelStyle: TextStyle(
                            color: _textColor.withOpacity(0.7),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(12),
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _borderColor),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          filled: true,
                          fillColor: _cardColor,
                          prefixIcon: Icon(
                            Icons.data_usage,
                            color: _primaryColor,
                          ),
                          suffix: DropdownButton<String>(
                            dropdownColor: _surfaceColor,
                            value: _selectedUnit,
                            items:
                                ['MB', 'GB'].map((String value) {
                                  return DropdownMenuItem<String>(
                                    value: value,
                                    child: Text(
                                      value,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                double newValueConverted;
                                double currentInputValue =
                                    double.tryParse(
                                      _limitBytesController.text,
                                    ) ??
                                    0;
                                int bytes;
                                switch (_selectedUnit) {
                                  case 'MB':
                                    bytes =
                                        (currentInputValue * 1024 * 1024)
                                            .round();
                                    break;
                                  case 'GB':
                                    bytes =
                                        (currentInputValue * 1024 * 1024 * 1024)
                                            .round();
                                    break;
                                  default:
                                    bytes =
                                        (currentInputValue * 1024 * 1024)
                                            .round();
                                }
                                switch (newValue) {
                                  case 'MB':
                                    newValueConverted = bytes / (1024 * 1024);
                                    break;
                                  case 'GB':
                                    newValueConverted =
                                        bytes / (1024 * 1024 * 1024);
                                    break;
                                  default:
                                    newValueConverted = bytes / (1024 * 1024);
                                }
                                setState(() {
                                  _selectedUnit = newValue;
                                  if (newValueConverted ==
                                      newValueConverted.roundToDouble()) {
                                    _limitBytesController.text =
                                        newValueConverted.round().toString();
                                  } else {
                                    _limitBytesController.text =
                                        newValueConverted.toStringAsFixed(1);
                                  }
                                });
                              }
                            },
                          ),
                        ),
                        keyboardType: TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(color: _textColor),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text('إلغاء', style: TextStyle(color: _textColor)),
                    ),
                    ElevatedButton(
                      onPressed: () => Navigator.pop(context, true),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: Text('حفظ'),
                    ),
                  ],
                ),
              );
            },
          ),
    );

    if (result == true) {
      try {
        final inputValue = double.tryParse(_limitBytesController.text) ?? 0;
        int bytes;
        switch (_selectedUnit) {
          case 'MB':
            bytes = (inputValue * 1024 * 1024).round();
            break;
          case 'GB':
            bytes = (inputValue * 1024 * 1024 * 1024).round();
            break;
          default:
            bytes = (inputValue * 1024 * 1024).round();
        }

        await widget.client.talk([
          '/ip/hotspot/user/set',
          '=.id=${user['.id']}',
          '=limit-bytes-total=$bytes',
        ]);

        final users = await _loadUsersFromJson();
        final updatedUsers =
            users.map((u) {
              if (u['.id'] == user['.id']) {
                return {...u, 'limit-bytes-total': bytes.toString()};
              }
              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('خطأ في التحديث: $e'),
            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(color: _accentColor)),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف المستخدم "${user['name']}"؟',
                style: TextStyle(color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text('إلغاء', style: TextStyle(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 {
        await widget.client.talk([
          '/ip/hotspot/user/remove',
          '=.id=${user['.id']}',
        ]);

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

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

        _loadUsers(page: _currentPage);
        if (_searchQuery.isNotEmpty) {
          _loadUsers(loadAllForSearch: true);
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('خطأ في الحذف: $e'),
            backgroundColor: _accentColor,
            behavior: SnackBarBehavior.floating,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
          ),
        );
      }
    }
  }

  void _showUserDetails(Map<String, dynamic> user) {
    showDialog(
      context: context,
      builder:
          (context) => Directionality(
            textDirection: TextDirection.rtl,
            child: Dialog(
              backgroundColor: _surfaceColor,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(16),
              ),
              child: Container(
                constraints: BoxConstraints(maxWidth: 500),
                padding: EdgeInsets.all(24),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          'تفاصيل المستخدم',
                          style: TextStyle(
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            color: _primaryColor,
                          ),
                        ),
                        IconButton(
                          icon: Icon(
                            Icons.close,
                            color: _textColor.withOpacity(0.7),
                          ),
                          onPressed: Navigator.of(context).pop,
                        ),
                      ],
                    ),
                    Divider(color: _borderColor),
                    SizedBox(height: 16),
                    SingleChildScrollView(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          _buildDetailRow('ID', _formatId(user['.id'])),
                          _buildDetailRow('الاسم', user['name'] ?? 'غير معروف'),
                          _buildDetailRow(
                            'كلمة المرور',
                            user['password'] ?? 'غير معروف',
                          ),
                          _buildDetailRow(
                            'البروفايل',
                            user['profile'] ?? 'غير معروف',
                          ),
                          _buildDetailRow(
                            'الحالة',
                            user['disabled'] == 'true' ? 'معطل' : 'نشط',
                          ),
                          _buildDetailRow(
                            'الحد الأقصى للبيانات',
                            _formatBytes(user['limit-bytes-total'] ?? 0),
                          ),
                          _buildDetailRow(
                            'مدة الاتصال',
                            _formatUptime(user['uptime']),
                          ),
                          _buildDetailRow(
                            'البيانات الواردة',
                            _formatBytes(user['bytes-in'] ?? 0),
                          ),
                          _buildDetailRow(
                            'البيانات الصادرة',
                            _formatBytes(user['bytes-out'] ?? 0),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(height: 24),
                    Center(
                      child: ElevatedButton(
                        onPressed: Navigator.of(context).pop,
                        style: ElevatedButton.styleFrom(
                          backgroundColor: _primaryColor,
                          foregroundColor: Colors.white,
                          padding: EdgeInsets.symmetric(
                            horizontal: 32,
                            vertical: 12,
                          ),
                          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(
              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(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(
                      fontSize: isMobile ? 12 : 14,
                      color: _textColor.withOpacity(0.8),
                    ),
                  ),
                  Text(
                    intl.NumberFormat.decimalPattern().format(_totalItems),
                    style: TextStyle(
                      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(color: _textColor.withOpacity(0.5)),
          labelStyle: TextStyle(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(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(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(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(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: _textColor.withOpacity(0.6),
            ),
          ),
          SizedBox(height: 8),
          Text(
            'جرب إضافة مستخدمين جدد.',
            style: TextStyle(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['name']?.toString().toLowerCase() ?? '';
      final profile = user['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) {
    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['name']?.toString().toLowerCase() ?? '';
            bValue = b['name']?.toString().toLowerCase() ?? '';
            break;
          case 2:
            aValue = a['profile']?.toString().toLowerCase() ?? '';
            bValue = b['profile']?.toString().toLowerCase() ?? '';
            break;
          case 3:
            aValue = a['disabled'] == 'true' ? 0 : 1;
            bValue = b['disabled'] == 'true' ? 0 : 1;
            break;
          case 4:
            aValue = _parseUptimeToSeconds(a['uptime']);
            bValue = _parseUptimeToSeconds(b['uptime']);
            break;
          case 5:
            aValue = int.tryParse(a['bytes-in']?.toString() ?? '0') ?? 0;
            bValue = int.tryParse(b['bytes-in']?.toString() ?? '0') ?? 0;
            break;
          case 6:
            aValue = int.tryParse(a['bytes-out']?.toString() ?? '0') ?? 0;
            bValue = int.tryParse(b['bytes-out']?.toString() ?? '0') ?? 0;
            break;
          case 7:
            aValue =
                int.tryParse(a['limit-bytes-total']?.toString() ?? '0') ?? 0;
            bValue =
                int.tryParse(b['limit-bytes-total']?.toString() ?? '0') ?? 0;
            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('خطأ في فرز البيانات: $e'),
          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(
                        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('مدة الاتصال'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('الواردة'),
                          numeric: true,
                          tooltip: 'البيانات الواردة',
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('الصادرة'),
                          numeric: true,
                          tooltip: 'البيانات الصادرة',
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('الحد الأقصى'),
                          numeric: true,
                          tooltip: 'الحد الأقصى للبيانات',
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(label: Text('الإجراءات')),
                      ],
                      rows:
                          usersToDisplay.map((user) {
                            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: 'monospace',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 120),
                                    child: Text(
                                      user['name'] ?? 'غير معروف',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color: _secondaryColor.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(
                                        color: _secondaryColor.withOpacity(0.3),
                                      ),
                                    ),
                                    child: Text(
                                      user['profile'] ?? 'غير معروف',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _secondaryColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 80),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          user['disabled'] == 'true'
                                              ? Colors.red.withOpacity(0.1)
                                              : _successColor.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(4),
                                      border: Border.all(
                                        color:
                                            user['disabled'] == 'true'
                                                ? Colors.red.withOpacity(0.3)
                                                : _successColor.withOpacity(
                                                  0.3,
                                                ),
                                      ),
                                    ),
                                    child: Text(
                                      user['disabled'] == 'true'
                                          ? 'معطل'
                                          : 'نشط',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color:
                                            user['disabled'] == 'true'
                                                ? Colors.red
                                                : _successColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatUptime(user['uptime']),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(user['bytes-in'] ?? 0),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _successColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(user['bytes-out'] ?? 0),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _accentColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(
                                        user['limit-bytes-total'] ?? 0,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(color: _warningColor),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 180),
                                    child: Row(
                                      mainAxisSize: MainAxisSize.min,
                                      children: [
                                        Tooltip(
                                          message: 'تعديل الحد الأقصى',
                                          child: InkWell(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                            onTap:
                                                () => _showEditLimitBytesDialog(
                                                  user,
                                                ),
                                            child: Container(
                                              padding: EdgeInsets.all(6),
                                              decoration: BoxDecoration(
                                                color: _warningColor
                                                    .withOpacity(0.1),
                                                borderRadius:
                                                    BorderRadius.circular(20),
                                              ),
                                              child: Icon(
                                                Icons.edit,
                                                size: 20,
                                                color: _warningColor,
                                              ),
                                            ),
                                          ),
                                        ),
                                        SizedBox(width: 8),
                                        Tooltip(
                                          message:
                                              user['disabled'] == 'true'
                                                  ? 'تفعيل المستخدم'
                                                  : 'تعطيل المستخدم',
                                          child: InkWell(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                            onTap:
                                                () => _toggleUserStatus(user),
                                            child: Container(
                                              padding: EdgeInsets.all(6),
                                              decoration: BoxDecoration(
                                                color:
                                                    user['disabled'] == 'true'
                                                        ? Colors.green
                                                            .withOpacity(0.1)
                                                        : Colors.red
                                                            .withOpacity(0.1),
                                                borderRadius:
                                                    BorderRadius.circular(20),
                                              ),
                                              child: Icon(
                                                user['disabled'] == 'true'
                                                    ? Icons.toggle_off
                                                    : Icons.toggle_on,
                                                size: 20,
                                                color:
                                                    user['disabled'] == 'true'
                                                        ? 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.builder(
      itemCount: usersToDisplay.length,
      itemBuilder: (context, index) {
        final user = usersToDisplay[index];
        final isDisabled = user['disabled'] == 'true';
        final uptime = _formatUptime(user['uptime']);
        final limitBytes = _formatBytes(user['limit-bytes-total'] ?? 0);
        final bytesIn = _formatBytes(user['bytes-in'] ?? 0);
        final bytesOut = _formatBytes(user['bytes-out'] ?? 0);
        final usagePercentage = _calculateUsagePercentage(user);

        return Container(
          margin: EdgeInsets.symmetric(vertical: 6, horizontal: 8),
          decoration: BoxDecoration(
            color: isDisabled ? _cardColor.withOpacity(0.6) : _cardColor,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(color: _borderColor.withOpacity(0.2), width: 1),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 8,
                offset: Offset(0, 3),
              ),
            ],
          ),
          child: Material(
            color: Colors.transparent,
            child: InkWell(
              borderRadius: BorderRadius.circular(12),
              onTap: () => _showUserDetails(user),
              splashColor: _primaryColor.withOpacity(0.1),
              highlightColor: _primaryColor.withOpacity(0.05),
              child: Padding(
                padding: EdgeInsets.all(12), // تقليل الحشو من 16 إلى 12
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Header Row (مضغوط أكثر)
                    Row(
                      children: [
                        // Checkbox أصغر
                        Transform.scale(
                          scale: 0.85,
                          child: Checkbox(
                            value: _selectedUsers.contains(user['.id']),
                            onChanged:
                                (bool? value) =>
                                    _handleUserSelection(user, value),
                            activeColor: _primaryColor,
                            materialTapTargetSize:
                                MaterialTapTargetSize.shrinkWrap,
                            visualDensity: VisualDensity.compact,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(4),
                            ),
                          ),
                        ),

                        SizedBox(width: 6), // تقليل المسافة من 8 إلى 6
                        // User Info
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // عرض ID
                              Container(
                                padding: EdgeInsets.symmetric(
                                  horizontal: 6,
                                  vertical: 2,
                                ),
                                decoration: BoxDecoration(
                                  color: _cardColor.withOpacity(0.7),
                                  borderRadius: BorderRadius.circular(4),
                                  border: Border.all(
                                    color: _primaryColor.withOpacity(0.3),
                                    width: 0.5,
                                  ),
                                ),
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    Icon(
                                      Icons.fingerprint,
                                      size: 12,
                                      color: _primaryColor.withOpacity(0.7),
                                    ),
                                    SizedBox(width: 4),
                                    Text(
                                      _formatId(user['.id']),
                                      style: TextStyle(
                                        fontSize: 10,
                                        fontFamily: 'monospace',
                                        color: _primaryColor,
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              // عرض اسم المستخدم
                              Text(
                                user['name'] ?? 'غير معروف',
                                style: TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 15,
                                  color:
                                      isDisabled ? Colors.grey : _primaryColor,
                                ),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ),
                              SizedBox(height: 2),
                              Row(
                                children: [
                                  Icon(
                                    Icons.timer_outlined,
                                    size: 13,
                                    color: _textColor.withOpacity(0.5),
                                  ),
                                  SizedBox(width: 3),
                                  Text(
                                    uptime,
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: _textColor.withOpacity(0.7),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),

                        // Profile Badge (أصغر)
                        Container(
                          padding: EdgeInsets.symmetric(
                            horizontal: 8, // تقليل من 10 إلى 8
                            vertical: 3, // تقليل من 4 إلى 3
                          ),
                          decoration: BoxDecoration(
                            color:
                                isDisabled
                                    ? Colors.grey.withOpacity(0.1)
                                    : _secondaryColor.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(
                              6,
                            ), // تقليل من 8 إلى 6
                            border: Border.all(
                              color:
                                  isDisabled
                                      ? Colors.grey.withOpacity(0.3)
                                      : _secondaryColor.withOpacity(0.3),
                            ),
                          ),
                          child: Text(
                            user['profile'] ?? 'غير معروف',
                            style: TextStyle(
                              fontSize: 11, // تقليل حجم الخط من 12 إلى 11
                              fontWeight: FontWeight.w500,
                              color: isDisabled ? Colors.grey : _secondaryColor,
                            ),
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 10), // تقليل من 16 إلى 10
                    // Usage Progress Bar (أصغر)
                    Column(
                      children: [
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              'استهلاك البيانات',
                              style: TextStyle(
                                fontSize: 11, // تقليل من 12 إلى 11
                                color: _textColor.withOpacity(0.7),
                              ),
                            ),
                            Text(
                              '${(usagePercentage * 100).toStringAsFixed(1)}%',
                              style: TextStyle(
                                fontSize: 11, // تقليل من 12 إلى 11
                                fontWeight: FontWeight.w500,
                                color: _primaryColor,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 4), // تقليل من 6 إلى 4
                        ClipRRect(
                          borderRadius: BorderRadius.circular(3),
                          child: LinearProgressIndicator(
                            value: usagePercentage,
                            backgroundColor: _borderColor.withOpacity(0.1),
                            color:
                                usagePercentage > 0.8
                                    ? Colors.orange
                                    : _primaryColor,
                            minHeight: 5, // تقليل من 6 إلى 5
                          ),
                        ),
                        SizedBox(height: 2), // تقليل من 4 إلى 2
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                              '0 MB',
                              style: TextStyle(
                                fontSize: 9, // تقليل من 10 إلى 9
                                color: _textColor.withOpacity(0.5),
                              ),
                            ),
                            Text(
                              limitBytes,
                              style: TextStyle(
                                fontSize: 9, // تقليل من 10 إلى 9
                                color: _textColor.withOpacity(0.5),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),

                    SizedBox(height: 10), // تقليل من 16 إلى 10
                    // Data Stats (مضغوط أكثر)
                    Container(
                      padding: EdgeInsets.all(8), // تقليل من 12 إلى 8
                      decoration: BoxDecoration(
                        color: Theme.of(context).cardColor.withOpacity(0.3),
                        borderRadius: BorderRadius.circular(
                          10,
                        ), // تقليل من 12 إلى 10
                      ),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceAround,
                        children: [
                          _buildCompactDataStat(
                            icon: Icons.download_rounded,
                            value: bytesIn,
                            color: _successColor,
                            label: 'تحميل',
                          ),
                          _buildCompactDataStat(
                            icon: Icons.upload_rounded,
                            value: bytesOut,
                            color: _accentColor,
                            label: 'رفع',
                          ),
                          _buildCompactDataStat(
                            icon: Icons.language_rounded,
                            value: limitBytes,
                            color: _warningColor,
                            label: 'الحد الأقصى',
                          ),
                        ],
                      ),
                    ),

                    SizedBox(height: 10), // تقليل من 16 إلى 10
                    // Action Buttons (أصغر)
                    Row(
                      children: [
                        Expanded(
                          child: _buildSmallActionButton(
                            icon: Icons.edit_rounded,
                            label: 'تعديل',
                            color: _warningColor,
                            onPressed: () => _showEditLimitBytesDialog(user),
                          ),
                        ),
                        SizedBox(width: 6), // تقليل من 8 إلى 6
                        Expanded(
                          child: _buildSmallActionButton(
                            icon:
                                isDisabled ? Icons.toggle_on : Icons.toggle_off,
                            label: isDisabled ? 'تفعيل' : 'تعطيل',
                            color: isDisabled ? Colors.green : Colors.red,
                            onPressed: () => _toggleUserStatus(user),
                          ),
                        ),
                        SizedBox(width: 6), // تقليل من 8 إلى 6
                        Expanded(
                          child: _buildSmallActionButton(
                            icon: Icons.delete_outline_rounded,
                            label: 'حذف',
                            color: _accentColor,
                            onPressed: () => _confirmDeleteUser(user),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  // دالة مساعدة لأزرار الإجراءات الأصغر
  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(
                  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(
            fontSize: 10, // تقليل حجم الخط من 12 إلى 10
            fontWeight: FontWeight.w500,
            color: _textColor.withOpacity(0.8),
          ),
        ),
        Text(
          label,
          style: TextStyle(
            fontSize: 9, // تقليل حجم الخط من 10 إلى 9
            color: _textColor.withOpacity(0.6),
          ),
        ),
      ],
    );
  }

  // دالة مساعدة لإنشاء أزرار الإجراءات
  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required Color color,
    required VoidCallback onPressed,
  }) {
    return OutlinedButton.icon(
      icon: Icon(icon, size: 18),
      label: Text(label),
      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)),
      ),
    );
  }

  // دالة مساعدة لعرض إحصائيات البيانات
  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(
            fontSize: 13,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        SizedBox(height: 2),
        Text(
          label,
          style: TextStyle(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(
                      color: _textColor.withOpacity(0.7),
                      fontSize: 12,
                    ),
                  ),
                  Text(
                    "$progressPercent%",
                    style: TextStyle(
                      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(
                          color: _primaryColor,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      TextSpan(
                        text: " / $totalPages",
                        style: TextStyle(
                          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(
                            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(
                            color: isActive ? Colors.white : Colors.grey[600],
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildDesktopLayout(BuildContext context) {
    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: Column(
              children: [
                const SizedBox(height: 40),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Icon(Icons.router, color: _primaryColor, size: 28),
                      const SizedBox(width: 10),
                      Text(
                        'لوحة تحكم الراوتر',
                        style: TextStyle(
                          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: _buildMainContent(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopNavigation() {
    return Column(
      children: [
        _buildNavItem(
          icon: Icons.dashboard,
          title: 'الرئيسية',
          isActive: false,
          onTap: () {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(
                builder: (context) => RouterDetailsPage(client: widget.client),
              ),
            );
          },
        ),
        _buildNavItem(
          icon: Icons.people,
          title: 'المستخدمون',
          isActive: true,
          onTap: () {},
        ),
        _buildNavItem(
          icon: Icons.person_add,
          title: 'إضافة مستخدم',
          isActive: false,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder:
                    (context) => AddHotspotCardsPage(client: widget.client),
              ),
            );
          },
        ),
        const SizedBox(height: 20),
        const Divider(color: Colors.white24, height: 1),
        _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: 16),
        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(
                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 build(BuildContext context) {
    final isMobile = MediaQuery.of(context).size.width < 768;

    return Directionality(
      textDirection: TextDirection.rtl,
      child: Scaffold(
        backgroundColor: _backgroundColor,
        appBar: AppBar(
          backgroundColor: _backgroundColor,
          elevation: 0,
          title: Text(
            isMobile ? 'مستخدمي الهوت سبوت' : 'إدارة مستخدمي الهوت سبوت',
            style: TextStyle(
              color: _textColor,
              fontWeight: FontWeight.bold,
              fontSize: isMobile ? 18 : 20,
            ),
          ),
          centerTitle: true,

          leading: IconButton(
            icon: Icon(
              Icons.arrow_back,
              color: _textColor,
              size: isMobile ? 20 : 24,
            ),
            onPressed: () => Navigator.of(context).pop(),
          ),
          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(
                          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 (!isMobile && !_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.add,
                label: 'إضافة رصيد',
                onPressed: _showAddBytesDialog,
                color: _primaryColor,
              ),
              _AppBarActionButton(
                icon: Icons.edit_note_rounded,
                label: 'تعديل',
                onPressed: _showEditSelectedUsersDialog,
                color: _secondaryColor,
              ),
              _AppBarActionButton(
                icon: Icons.person_remove_alt_1_rounded,
                label: 'حذف',
                onPressed: _deleteSelectedUsers,
                color: _accentColor,
              ),
              _AppBarActionButton(
                icon: Icons.delete_sweep,
                label: 'تنظيف',
                onPressed: _deleteExpiredUsers,
                color: Colors.orange,
              ),
            ],
          ],
        ),
        body: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildUserCountBanner(),
              SizedBox(height: 1),
              LayoutBuilder(
                builder: (context, constraints) {
                  if (constraints.maxWidth > 400) {
                    return Row(
                      children: [
                        Expanded(
                          child: SizedBox(height: 48, child: _buildSearchBar()),
                        ),
                        SizedBox(width: 8),
                        SizedBox(
                          height: 48,
                          child: _buildItemsPerPageControl(),
                        ),
                      ],
                    );
                  } else {
                    return 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 (isMobile && !_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(
                                                      fontSize: 12,
                                                      color:
                                                          _selectedUsers.length ==
                                                                      _filteredUsers
                                                                          .length &&
                                                                  _selectedUsers
                                                                      .isNotEmpty
                                                              ? _primaryColor
                                                              : _textColor
                                                                  .withOpacity(
                                                                    0.7,
                                                                  ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                      _SmallActionButton(
                                        icon: Icons.add,
                                        label: 'إضافة',
                                        onPressed: _showAddBytesDialog,
                                        color: _primaryColor,
                                      ),
                                      _SmallActionButton(
                                        icon: Icons.edit_note_rounded,
                                        label: 'تعديل',
                                        onPressed: _showEditSelectedUsersDialog,
                                        color: _secondaryColor,
                                      ),
                                      _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:
                                    isMobile
                                        ? _buildMobileList()
                                        : _buildDesktopTable(),
                              ),
                              if (!_searchingAllData)
                                _buildPaginationControls(),
                            ],
                          ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

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(
                      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(fontSize: 12, color: color)),
            ],
          ),
        ),
      ),
    );
  }
}


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