لماذا يتم تحديث الواجهه باكملها عند تغيير حال ال checkbox الى checked في وضع شاشة الهاتف 
للعلم الكود
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:micro_panel/AboutApp.dart';
import 'package:micro_panel/AddHotspotUser.dart';
import 'package:micro_panel/AddUserManagerUser.dart';
import 'package:micro_panel/HelpDesk.dart';
import 'package:micro_panel/HomePage.dart';
import 'package:micro_panel/HotspotProfile.dart';
import 'package:micro_panel/Login.dart';
import 'package:micro_panel/SendNotes.dart';
import 'package:micro_panel/UserManagerProfile.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/UserManagerUserList.dart';
import 'package:micro_panel/backupSN.dart';
import 'package:micro_panel/free_rebiuld.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);
  bool isHotspotExpanded = true;
  bool isUserManagerExpanded = false;
  bool isSettingsExpanded = false;
  bool isHelpExpanded = false;

  Future<File> _getJsonFile() async {
    final maindirectory = await getApplicationDocumentsDirectory();
    final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
    if (!await saveDirectory.exists()) {
      await saveDirectory.create(recursive: true);
    }
    final filePath = path.join(saveDirectory.path, '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(
              fontFamily: 'Tajawal',
              fontSize: isMobile ? 18 : 22,
              fontWeight: FontWeight.bold,
              color: _primaryColor,
            ),
          ),
        ],
      ),
    );
  }

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

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

  Future<void> _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(
                      fontFamily: 'Tajawal',
                      color: _primaryColor,
                    ),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextFormField(
                        controller: _addBytesController,
                        decoration: InputDecoration(
                          labelText: 'كمية البيانات المضافة',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            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(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _addBytesUnit = newValue);
                              }
                            },
                          ),
                        ),
                        keyboardType: TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                      ),
                      SizedBox(height: 16),
                      Text(
                        'سيتم إضافة هذه الكمية إلى الرصيد الحالي للمستخدمين المحددين',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.5),
                        ),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text(
                        'إلغاء',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          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(
                      fontFamily: 'Tajawal',
                      color: _primaryColor,
                    ),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      TextFormField(
                        controller: _limitBytesController,
                        decoration: InputDecoration(
                          labelText: 'الحد الأقصى للبيانات',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            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(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              if (newValue != null) {
                                setState(() => _selectedUnit = newValue);
                              }
                            },
                          ),
                        ),
                        keyboardType: TextInputType.numberWithOptions(
                          decimal: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                      ),
                      SizedBox(height: 16),
                      Text(
                        'سيتم تعيين هذا الرصيد للمستخدمين المحددين (${_selectedUsers.length})',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.5),
                        ),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text(
                        'إلغاء',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          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(fontFamily: 'Tajawal', color: _accentColor),
              ),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف ${_selectedUsers.length} مستخدم؟',
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text(
                    'إلغاء',
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _accentColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Text('حذف'),
                ),
              ],
            ),
          ),
    );

    if (confirmed == true) {
      try {
        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();
    Future.delayed(Duration(milliseconds: 100), () {
      _loadUsersFromJson().then((users) {
        setState(() {
          _users = users.take(_itemsPerPage).toList();
          _totalItems = users.length;
          _isLoading = false;
        });
      });

      _searchController.addListener(_handleSearch);
      _scrollController.addListener(_scrollListener);
      _loadTotalUsers();
    });
  }

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

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

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

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

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

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

      // تصفية جميع النتائج مرة واحدة (يمكن تحسين هذا ليكون على الخادم في المستقبل)
      final filteredUsers =
          allUsers.where((user) {
            final name = user['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) {
        await _scrollController.animateTo(
          0,
          duration: Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    } catch (e) {
      setState(() => _isLoading = false);
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'خطأ في البحث',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          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(
            'خطأ في جلب البيانات',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          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(
            'خطأ في تعديل الحالة',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          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(
                      fontFamily: 'Tajawal',
                      color: _primaryColor,
                    ),
                  ),
                  content: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        'اسم المستخدم: ${user['name']}',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                      ),
                      SizedBox(height: 16),
                      TextFormField(
                        controller: _limitBytesController,
                        decoration: InputDecoration(
                          labelText: 'الحد الأقصى للبيانات',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            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(
                                        fontFamily: 'Tajawal',
                                        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(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                      ),
                    ],
                  ),
                  actions: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      child: Text(
                        'إلغاء',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          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(fontFamily: 'Tajawal', color: _accentColor),
              ),
              content: Text(
                'هل أنت متأكد من رغبتك في حذف المستخدم "${user['name']}"؟',
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.pop(context, false),
                  child: Text(
                    'إلغاء',
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                  ),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.pop(context, true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _accentColor,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(12),
                    ),
                  ),
                  child: Text('حذف'),
                ),
              ],
            ),
          ),
    );

    if (confirmed == true) {
      try {
        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),
            ),
          ),
        );
      }
    }
  }

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

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

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

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

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

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

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

  List<Map<String, dynamic>> get _filteredUsers {
    if (_searchQuery.isEmpty) return _users;
    final searchLower = _searchQuery.toLowerCase();
    final sourceList =
        _searchingAllData || _allUsersForSearch.isNotEmpty
            ? _allUsersForSearch
            : _users;
    return sourceList.where((user) {
      final name = user['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;
          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),
          ),
        ),
      );
    }
  }

  Widget _buildDesktopTable() {
    final usersToDisplay = _searchQuery.isNotEmpty ? _filteredUsers : _users;
    return Column(
      children: [
        Expanded(
          child: LayoutBuilder(
            builder: (context, constraints) {
              return SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                child: ConstrainedBox(
                  constraints: BoxConstraints(minWidth: constraints.maxWidth),
                  child: SingleChildScrollView(
                    scrollDirection: Axis.vertical,
                    child: DataTable(
                      headingRowColor: MaterialStateProperty.resolveWith(
                        (states) => _cardColor,
                      ),
                      headingTextStyle: TextStyle(
                        fontFamily: 'Tajawal',
                        fontWeight: FontWeight.bold,
                        color: _primaryColor,
                      ),
                      dataRowColor: MaterialStateProperty.resolveWith(
                        (states) => _surfaceColor,
                      ),
                      dividerThickness: 0,
                      columnSpacing: 16,
                      sortColumnIndex: _sortColumnIndex,
                      sortAscending: _sortAscending,
                      columns: [
                        DataColumn(label: Text('تحديد')),
                        DataColumn(
                          label: Text('ID'),
                          numeric: true,
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('الاسم'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('البروفايل'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('الحالة'),
                          onSort:
                              (columnIndex, ascending) =>
                                  _sortUsers(columnIndex, ascending),
                        ),
                        DataColumn(
                          label: Text('وقت التشغيل'),
                          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: 'Tajawal',

                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 120),
                                    child: Text(
                                      user['name'] ?? 'غير معروف',
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    padding: EdgeInsets.symmetric(
                                      horizontal: 8,
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color: _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(
                                        fontFamily: 'Tajawal',
                                        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(
                                        fontFamily: 'Tajawal',
                                        color:
                                            user['disabled'] == 'true'
                                                ? Colors.red
                                                : _successColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatUptime(user['uptime']),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _textColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(user['bytes-in'] ?? 0),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _successColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(user['bytes-out'] ?? 0),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: _accentColor,
                                      ),
                                    ),
                                  ),
                                ),
                                DataCell(
                                  Container(
                                    constraints: BoxConstraints(maxWidth: 100),
                                    child: Text(
                                      _formatBytes(
                                        user['limit-bytes-total'] ?? 0,
                                      ),
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        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.separated(
      itemCount: usersToDisplay.length,
      padding: EdgeInsets.symmetric(vertical: 5, horizontal: 3),
      separatorBuilder: (context, index) => SizedBox(height: 8),
      itemBuilder: (context, index) {
        final user = usersToDisplay[index];
        final isDisabled = user['disabled'] == 'true';
        final uptime = _formatUptime(user['uptime']);
        final limitBytes = _formatBytes(user['limit-bytes-total'] ?? 0);
        final bytesIn = _formatBytes(user['bytes-in'] ?? 0);
        final bytesOut = _formatBytes(user['bytes-out'] ?? 0);
        final usagePercentage = _calculateUsagePercentage(user);

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

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

  Widget _buildUserName(Map<String, dynamic> user, bool isDisabled) {
    return Text(
      user['name'] ?? 'غير معروف',
      style: TextStyle(
        fontFamily: 'Tajawal',
        fontSize: 16,
        fontWeight: FontWeight.w700,
        color: isDisabled ? Colors.grey[500] : _textColor,
        height: 1.2,
      ),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
    );
  }

  Widget _buildUserSubtitle(Map<String, dynamic> user) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(height: 4),
        Wrap(
          spacing: 8,
          crossAxisAlignment: WrapCrossAlignment.center,
          children: [
            Chip(
              label: Text(
                _formatId(user['.id']),
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  fontSize: 10,
                  height: 1.2,
                ),
              ),
              backgroundColor: _cardColor.withOpacity(0.3),
              visualDensity: VisualDensity.compact,
              labelPadding: EdgeInsets.symmetric(horizontal: 6),
              materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
            ),
            Text(
              user['profile'] ?? 'غير معروف',
              style: TextStyle(
                fontFamily: 'Tajawal',
                fontSize: 12,
                color: _textColor.withOpacity(0.7),
              ),
            ),
          ],
        ),
      ],
    );
  }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        SizedBox(height: 16),

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

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

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

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

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

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

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

  Widget _buildMobileLayout() {
    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    return Scaffold(
      backgroundColor: _backgroundColor,
      key: _scaffoldKey,
      drawer: Drawer(child: _buildUniversalDrawer()),
      appBar: AppBar(
        backgroundColor: _backgroundColor,
        elevation: 0,
        title: Text(
          'مستخدمي الهوت سبوت',
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: _textColor,
            fontWeight: FontWeight.bold,
            fontSize: 18,
          ),
        ),
        centerTitle: true,

        actions: [
          if (_selectedUsers.isNotEmpty)
            AnimatedSwitcher(
              duration: Duration(milliseconds: 300),
              child: Container(
                key: ValueKey<int>(_selectedUsers.length),
                margin: EdgeInsets.symmetric(horizontal: 8),
                padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: _secondaryColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(color: _secondaryColor.withOpacity(0.3)),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Icon(
                      Icons.check_circle_rounded,
                      size: 18,
                      color: _secondaryColor,
                    ),
                    SizedBox(width: 6),
                    Text(
                      '${_selectedUsers.length}',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                        color: _secondaryColor,
                      ),
                    ),
                    SizedBox(width: 6),
                    InkWell(
                      borderRadius: BorderRadius.circular(12),
                      onTap: () => setState(() => _selectedUsers.clear()),
                      child: Padding(
                        padding: EdgeInsets.all(4),
                        child: Icon(
                          Icons.close,
                          size: 16,
                          color: _secondaryColor.withOpacity(0.7),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
        ],
        leading: IconButton(
          icon: Icon(Icons.menu, color: _textColor),
          onPressed: () {
            _scaffoldKey.currentState?.openDrawer(); // ✅ هذا هو الفتح المطلوب
          },
        ),
      ),

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

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

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

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

              // User Manager Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(
                      Icons.manage_accounts,
                      color: Colors.white.withOpacity(0.7),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة اليوزر مانجر',
                      style: TextStyle(
                        fontFamily: 'Tajawal',

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

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

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

              const Divider(color: Colors.white24),

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

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

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

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

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

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

                _buildNavItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  isActive: false,
                  onTap: () {
                    UserManagerSession(client: widget.client);
                  },
                ),
              ],
            ),

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

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

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

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

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

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

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

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

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

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

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

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

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


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