في حال ظهرت اي رسالة هنا اي رسالة حدث خطاء اريد ان يتم ارسالي الى صفحة ال login
الكود
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:micro_panel/AddUserManagerUser.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/UserManagerUserList.dart';
import 'package:router_os_client/router_os_client.dart';
import 'Login.dart';
import 'hotspotUserList.dart';
import 'AddHotspotUser.dart';
import 'package:flutter/scheduler.dart';

class RouterDetailsPage extends StatefulWidget {
  final RouterOSClient client;
  const RouterDetailsPage({super.key, required this.client});

  @override
  State<RouterDetailsPage> createState() => _RouterDetailsPageState();
}

class _RouterDetailsPageState extends State<RouterDetailsPage> {
  final _routerInfoNotifier = ValueNotifier<Map<String, dynamic>>({});
  final _activeHotspotUsersCountNotifier = ValueNotifier<int>(0);
  final _connectedDevicesCountNotifier = ValueNotifier<int>(0);
  final _isLoadingNotifier = ValueNotifier<bool>(false);
  final _hasErrorNotifier = ValueNotifier<bool>(false);
  Timer? _uptimeTimer, _cpuTimer, _memoryTimer, _usersTimer, _devicesTimer;
  bool _isFetchingUsers = false;
  bool _isFetchingDevices = false;
  int _lastKnownUserCount = 0;
  int _currentIndex = 0;
  Color _primaryColor = const Color(0xFF3B82F6);
  Color _backgroundColor = const Color(0xFF0A192F);
  Color _cardColor = const Color(0xFF172A46);
  Color _textColor = Colors.white;
  TickerProvider? _tickerProvider;
  Timer? _mainTimer; // أضف هذا مع باقي المتغيرات في أعلى الكلاس

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

  Ticker? _uptimeTicker;
  Ticker? _cpuTicker;
  Ticker? _usersTicker;

  @override
  void initState() {
    super.initState();
    _startTimers();
    final client = AppSession().client;
    if (AppSession().client == null) {
      AppSession().client = widget.client;
      print("Client saved to AppSession");
    } else {
      print("Client already exists in AppSession");
    }
  }

  @override
  void dispose() {
    _cancelAllTimers();
    _uptimeTicker?.dispose();
    _cpuTicker?.dispose();
    _usersTicker?.dispose();
    _uptimeTimer?.cancel();
    widget.client.close();
    _routerInfoNotifier.dispose();
    _activeHotspotUsersCountNotifier.dispose();
    _connectedDevicesCountNotifier.dispose();
    _isLoadingNotifier.dispose();
    _hasErrorNotifier.dispose();
    super.dispose();
  }

  void _cancelAllTimers() {
    _uptimeTimer?.cancel();
    _uptimeTimer = null;

    _cpuTimer?.cancel();
    _cpuTimer = null;

    _memoryTimer?.cancel();
    _memoryTimer = null;

    _usersTimer?.cancel();
    _usersTimer = null;

    _devicesTimer?.cancel();
    _devicesTimer = null;

    _mainTimer?.cancel(); // إضافة هذا السطر
    _mainTimer = null;

    print('All timers stopped');
  }

  void _startTimers() {
    _cancelAllTimers();

    // مؤقت واحد لجميع العمليات
    _mainTimer = Timer.periodic(Duration(seconds: 2), (timer) {
      if (!mounted) {
        // التحقق مما إذا كانت الواجهة لا تزال نشطة
        timer.cancel();
        return;
      }

      _updateUptime();

      if (timer.tick % 5 == 0) {
        // كل 10 ثوانٍ (2 * 5)
        _fetchActiveHotspotUsers();
      }

      if (timer.tick % 3 == 0) {
        // كل 6 ثوانٍ (2 * 3)
        _fetchCpu();
      }
    });

    _fetchAllData(); // الجلب الأولي للبيانات
  }

  void _updateUptime() {
    final currentUptime = _routerInfoNotifier.value['uptime'];
    if (currentUptime != null) {
      final newData = Map<String, dynamic>.from(_routerInfoNotifier.value);
      newData['uptime'] = _incrementUptime(currentUptime);
      _routerInfoNotifier.value = newData;
    }
  }

  String _incrementUptime(String uptime) {
    try {
      // تحليل الـ uptime الحالي وإضافة ثانية واحدة
      final parts = uptime.split(RegExp(r'h|m|s'));
      int hours = 0, minutes = 0, seconds = 0;

      if (uptime.contains('h')) hours = int.parse(parts[0]);
      if (uptime.contains('m'))
        minutes = int.parse(parts[uptime.contains('h') ? 1 : 0]);
      if (uptime.contains('s'))
        seconds = int.parse(
          parts[uptime.contains('m') ? 2 : (uptime.contains('h') ? 1 : 0)],
        );

      seconds += 1;

      if (seconds >= 60) {
        seconds = 0;
        minutes += 1;
      }
      if (minutes >= 60) {
        minutes = 0;
        hours += 1;
      }

      return '${hours}h${minutes}m${seconds}s';
    } catch (e) {
      return uptime;
    }
  }

  Future<void> _fetchAllData() async {
    await Future.wait([
      _fetchUptime(),
      _fetchCpu(),
      _fetchMemory(),
      Future.delayed(
        Duration(milliseconds: 450),
        () => _fetchActiveHotspotUsers(),
      ),
      Future.delayed(
        Duration(milliseconds: 600),
        () => _fetchConnectedDevices(),
      ),
    ]);
    await Future.delayed(Duration(seconds: 1));
    await _fetchCpu();
    print('first_fetch');
  }

  Future<void> _fetchResourceData(List<String> properties) async {
    try {
      final response = await widget.client.talk(['/system/resource/print']);
      if (response.isNotEmpty && response[0] is Map) {
        final data = Map<String, dynamic>.from(
          response[0] as Map<dynamic, dynamic>,
        );
        final newData = Map<String, dynamic>.from(_routerInfoNotifier.value);
        for (var prop in properties) {
          if (data.containsKey(prop)) {
            newData[prop] = data[prop];
          }
        }
        _routerInfoNotifier.value = newData;
      }
    } catch (e) {
      if (mounted) {
        _handleError(e);
      }
    }
  }

  Future<void> _fetchUptime() async => _fetchResourceData([
    'uptime',
    'identity',
    'version',
    'board-name',
    'cpu',
  ]);
  Future<void> _fetchCpu() async => _fetchResourceData(['cpu-load']);
  Future<void> _fetchMemory() async =>
      _fetchResourceData(['total-memory', 'free-memory']);

  Future<void> _fetchActiveHotspotUsers() async {
    if (_isFetchingUsers) return;
    _isFetchingUsers = true;
    dynamic response;

    try {
      response = await widget.client.talk([
        '/ip/hotspot/active/print',
        '=count-only=',
        '.tag=7',
      ]);

      int activeUsersCount = 0;

      if (response != null && response.isNotEmpty) {
        if (response[0] is Map && (response[0] as Map).containsKey('ret')) {
          activeUsersCount =
              int.tryParse((response[0] as Map)['ret'].toString()) ?? 0;
        } else {
          print('Response ignored: does not contain "ret" key.');
        }
      }

      if (_lastKnownUserCount != activeUsersCount) {
        _lastKnownUserCount = activeUsersCount;
        print('Active Users Count: $activeUsersCount');
        _activeHotspotUsersCountNotifier.value = activeUsersCount;
      }
    } catch (e) {
      if (mounted) _handleError(e);
      print('خطأ في جلب عدد المستخدمين');
    } finally {
      _isFetchingUsers = false;
    }
  }

  Future<void> _fetchConnectedDevices() async {
    if (_isFetchingDevices) return;
    _isFetchingDevices = true;
    dynamic response;

    try {
      response = await widget.client.talk([
        '/ip/neighbor/print',
        '=count-only=',
        '.tag=9',
      ]);

      int count = 0;

      if (response != null && response.isNotEmpty) {
        if (response[0] is Map && (response[0] as Map).containsKey('ret')) {
          count = int.tryParse((response[0] as Map)['ret'].toString()) ?? 0;
        } else {
          print('Response ignored: does not contain "ret" key.');
        }
      }

      if (_connectedDevicesCountNotifier.value != count) {
        print('Connected Devices Count: $count');
        _connectedDevicesCountNotifier.value = count;
      }
    } catch (e) {
      if (mounted) _handleError(e);
      print('خطأ في جلب اجهزة البث');
      if (response != null) {
        print('Response: $response');
      }
    } finally {
      _isFetchingDevices = false;
    }
  }

  void _handleError(dynamic e) {
    if (!mounted) return;
    _hasErrorNotifier.value = true;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          'حدث خطاء في عملية جلب البيانات من الراوتر',
          style: TextStyle(fontFamily: 'Tajawal'),
        ),
        backgroundColor: Colors.red,
      ),
    );
  }

  void _onItemTapped(int index) {
    setState(() {
      _currentIndex = index;
    });

    switch (index) {
      case 0:
        _cancelAllTimers(); // إيقاف المؤقتات قبل الانتقال
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => RouterDetailsPage(client: widget.client),
          ),
        ).then((_) {
          _startTimers(); // إعادة تشغيل المؤقتات عند العودة
        });
        break;
      case 1:
        _cancelAllTimers();
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => UsersPage(client: widget.client),
          ),
        ).then((_) {
          _startTimers();
        });
        break;
      case 2:
        _cancelAllTimers();
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddHotspotCardsPage(client: widget.client),
          ),
        ).then((_) {
          _startTimers();
        });
        break;
      case 3:
        _cancelAllTimers();
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Login()),
        );
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth > 800) {
            return _buildDesktopLayout(context);
          } else {
            return _buildMobileLayout(context);
          }
        },
      ),
    );
  }

  Widget _buildDesktopLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      body: Row(
        children: [
          Container(
            width: 280,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.05),
              border: Border(
                right: BorderSide(color: Colors.white.withOpacity(0.1)),
              ),
            ),
            child: Column(
              children: [
                // إضافة عرض وقت التشغيل هنا
                ValueListenableBuilder<Map<String, dynamic>>(
                  valueListenable: _routerInfoNotifier,
                  builder: (context, value, _) {
                    return UptimeDisplay(
                      uptime: value['uptime'],
                      version: value['version'],
                      boardName: value['board-name'],
                      isMobile: false,
                    );
                  },
                ),
                Expanded(
                  child: SingleChildScrollView(
                    child: _buildDesktopNavigation(),
                  ),
                ),
              ],
            ),
          ),

          Expanded(
            child: Column(
              children: [
                // شريط العنوان الجديد
                Container(
                  height: 60,
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.05),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.menu, color: _textColor),
                        onPressed: () {},
                        padding: EdgeInsets.zero,
                      ),
                      SizedBox(width: 5),
                      Expanded(
                        child: Text(
                          'لوحة تحكم الراوتر',
                          style: TextStyle(
                            color: _textColor,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Tajawal',
                          ),
                        ),
                      ),
                    ],
                  ),
                ),

                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: [
                        SizedBox(height: 10),
                        // الجزء الثابت في الأعلى (البطاقة الإحصائية)
                        Container(
                          padding: const EdgeInsets.all(16),
                          child: _buildAdaptiveStatsCard(),
                        ),

                        const SizedBox(height: 5),
                        Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 16),
                          child: Row(
                            children: [
                              Icon(
                                Icons.bar_chart,
                                color: _primaryColor,
                                size: 28,
                              ),
                              const SizedBox(width: 10),
                              Text(
                                'موارد النظام',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 20,
                                  fontWeight: FontWeight.bold,
                                  fontFamily: 'Tajawal',
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(
                          height: 20,
                        ), // الجزء القابل للتمرير (بقية المحتوى)
                        Expanded(
                          child: SingleChildScrollView(
                            padding: const EdgeInsets.symmetric(horizontal: 16),
                            child: Column(
                              children: [
                                const SizedBox(height: 5),
                                Row(
                                  children: [
                                    Expanded(child: _buildCpuUsageCard()),
                                    const SizedBox(width: 20),
                                    Expanded(child: _buildMemoryUsageCard()),
                                  ],
                                ),
                                const SizedBox(height: 20),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  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 _buildDesktopNavigation() {
    return Container(
      height: MediaQuery.of(context).size.height,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          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: true,
              onTap: () {},
            ),

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

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

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

            // قسم الإعدادات والأدوات (قابل للطي)
            _buildExpandableSection(
              title: 'الإعدادات والأدوات',
              icon: Icons.settings,
              initiallyExpanded: isSettingsExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isSettingsExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.settings,
                  title: 'إعدادات النظام',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.security,
                  title: 'الأمان',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.cloud,
                  title: 'التحديثات',
                  isActive: false,
                  onTap: () {},
                ),
              ],
            ),

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

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

  Widget _buildMobileLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      appBar: AppBar(
        title: Text(
          'لوحة تحكم الراوتر',
          style: TextStyle(
            color: _textColor,
            fontSize: 20,
            fontFamily: 'Tajawal',
          ),
        ),
        centerTitle: true,
        backgroundColor: _backgroundColor,
        elevation: 0,
        iconTheme: IconThemeData(color: _textColor),
      ),
      drawer: _buildUniversalDrawer(),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              _backgroundColor.withOpacity(0.9),
              _backgroundColor.withOpacity(0.7),
            ],
          ),
        ),
        child: SingleChildScrollView(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              _buildAdaptiveStatsCard(),
              const SizedBox(height: 20),
              _buildCpuUsageCard(),
              const SizedBox(height: 20),
              _buildMemoryUsageCard(),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUniversalDrawer() {
    return Drawer(
      backgroundColor: _backgroundColor,

      child: SafeArea(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            Container(
              height: 180,
              decoration: BoxDecoration(
                color: _primaryColor.withOpacity(0.1),
                border: Border(
                  bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
                ),
              ),
              padding: EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.network_check, size: 30, color: Colors.white),
                      const SizedBox(width: 8),
                      ValueListenableBuilder(
                        valueListenable: _routerInfoNotifier,
                        builder:
                            (context, value, _) => Text(
                              value['identity'] ?? 'Micro Panel',
                              style: const TextStyle(
                                fontFamily: 'Tajawal',
                                color: Colors.white,
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                      ),
                    ],
                  ),

                  const SizedBox(height: 9),
                  ValueListenableBuilder<Map<String, dynamic>>(
                    valueListenable: _routerInfoNotifier,
                    builder: (context, value, _) {
                      // استبدال UptimeDisplay بالمكون الجديد لشاشة الهاتف
                      return MobileUptimeDrawerItem(
                        uptime: value['uptime'],
                        version: value['version'],
                        boardName: value['board-name'],
                      );
                    },
                  ),
                ],
              ),
            ),

            // Main Navigation Items
            _buildUniversalDrawerItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              onTap: () {},
            ),

            // Hotspot Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة الهوتسبوت',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.person_add,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.group_add,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
              ],
            ),

            // 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: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.payment_rounded,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.credit_score,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  onTap: () {
                    _cancelAllTimers();

                    Navigator.push(
                      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),
                      ),
                    ).then((value) {
                      _startTimers();
                    });
                  },
                ),
              ],
            ),

            // Settings Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'الإعدادات والأدوات',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.settings,
                  title: 'إعدادات النظام',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.security,
                  title: 'الأمان',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.cloud,
                  title: 'التحديثات',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),

            // Help Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.help, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'المساعدة والدعم',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.help_outline,
                  title: 'المركز المساعدة',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),

            const Divider(color: Colors.white24),

            // Logout Item
            _buildUniversalDrawerItem(
              icon: Icons.logout,
              title: 'تسجيل خروج',
              color: Colors.red,
              onTap: () {
                _cancelAllTimers();

                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) => Login(),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildUniversalDrawerItem({
    required IconData icon,
    required String title,
    Color color = Colors.white,
    required VoidCallback onTap,
  }) {
    return ListTile(
      leading: Icon(icon, color: color),
      title: Text(
        title,
        style: TextStyle(color: color, fontSize: 14, fontFamily: 'Tajawal'),
      ),
      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(color: color, fontFamily: 'Tajawal')),
      onTap: onTap,
    );
  }

  Widget _buildAdaptiveStatsCard() {
    // ارتفاع ثابت لجميع الشاشات
    const double fixedHeight = 130.0;
    // أحجام ثابتة مع ضبطها لتكون متناسبة مع الارتفاع الثابت
    const double iconSize = 28.0;
    const double valueSize = 22.0;
    const double titleSize = 14.0;

    return LayoutBuilder(
      // أضف LayoutBuilder هنا
      builder: (context, constraints) {
        return Container(
          height: fixedHeight, // استخدام الارتفاع الثابت هنا
          decoration: BoxDecoration(
            color: _cardColor,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 10,
                spreadRadius: 2,
              ),
            ],
          ),
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: ValueListenableBuilder(
              valueListenable: _routerInfoNotifier,
              builder: (context, routerInfo, _) {
                return Row(
                  children: [
                    Expanded(
                      child: _buildStatItem(
                        icon: Icons.people_alt_outlined,
                        value:
                            _activeHotspotUsersCountNotifier.value.toString(),
                        title:
                            constraints.maxWidth > 800
                                ? 'المستخدمون النشطون'
                                : 'النشطون',
                        color: Colors.green,
                        iconSize: iconSize,
                        valueSize: valueSize,
                        titleSize: titleSize,
                      ),
                    ),
                    Container(
                      width: 1,
                      height: 60,
                      margin: EdgeInsets.symmetric(vertical: 12),
                      color: Colors.white.withOpacity(0.15),
                    ),
                    Expanded(
                      child: _buildStatItem(
                        icon: Icons.devices_other,
                        value: _connectedDevicesCountNotifier.value.toString(),
                        title:
                            constraints.maxWidth > 800
                                ? 'اجهزة البث'
                                : 'الأبراج',
                        color: Colors.blueAccent,
                        iconSize: iconSize,
                        valueSize: valueSize,
                        titleSize: titleSize,
                      ),
                    ),
                    Container(
                      width: 1,
                      height: 60,
                      margin: EdgeInsets.symmetric(vertical: 12),
                      color: Colors.white.withOpacity(0.15),
                    ),
                    Expanded(
                      child: _buildStatItem(
                        icon: Icons.health_and_safety,
                        value: _getSystemStatusFromMap(routerInfo),
                        title:
                            constraints.maxWidth > 800
                                ? 'حالة النظام'
                                : 'الحالة',
                        color: _getSystemStatusColorFromMap(routerInfo),
                        iconSize: iconSize,
                        valueSize: valueSize,
                        titleSize: titleSize,
                      ),
                    ),
                  ],
                );
              },
            ),
          ),
        );
      },
    );
  }

  Widget _buildStatItem({
    required IconData icon,
    required String value,
    required String title,
    required Color color,
    required double iconSize,
    required double valueSize,
    required double titleSize,
  }) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Icon(icon, size: iconSize, color: color),
        SizedBox(height: 6),
        Text(
          value,
          style: TextStyle(
            fontSize: valueSize,
            fontWeight: FontWeight.bold,
            color: color,
            fontFamily: 'Tajawal',
          ),
        ),
        SizedBox(height: 4),
        Text(
          title,
          style: TextStyle(
            color: Colors.white.withOpacity(0.9),
            fontSize: titleSize,
            fontFamily: 'Tajawal',
          ),
        ),
      ],
    );
  }

  Widget _buildHorizontalStatsLayout({
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
    required Map<String, dynamic> routerInfo,
    required BoxConstraints constraints,
  }) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: _cardColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            blurRadius: 12,
            spreadRadius: 3,
          ),
        ],
      ),
      child: Padding(
        padding: EdgeInsets.all(8),
        child: Row(
          children: [
            Expanded(
              child: _buildEnhancedStatItem(
                icon: Icons.people_alt_outlined,
                value: _activeHotspotUsersCountNotifier.value.toString(),
                title:
                    constraints.maxWidth > 800
                        ? 'المستخدمون النشطون'
                        : 'النشطون',
                color: Colors.green,
                iconSize: 28,
                valueSize: 24,
                titleSize: 16,
                spacing: 8,
              ),
            ),
            Container(
              width: 1,
              height: 60,
              margin: EdgeInsets.symmetric(vertical: 12),
              color: Colors.white.withOpacity(0.15),
            ),
            Expanded(
              child: _buildEnhancedStatItem(
                icon: Icons.devices_other,
                value: _connectedDevicesCountNotifier.value.toString(),
                title: constraints.maxWidth > 800 ? 'اجهزة البث' : 'الأبراج',
                color: Colors.blueAccent,
                iconSize: 28,
                valueSize: 24,
                titleSize: 16,
                spacing: 8,
              ),
            ),
            Container(
              width: 1,
              height: 60,
              margin: EdgeInsets.symmetric(vertical: 12),
              color: Colors.white.withOpacity(0.15),
            ),
            Expanded(
              child: _buildEnhancedStatItem(
                icon: Icons.health_and_safety,
                value: _getSystemStatusFromMap(routerInfo),
                title: constraints.maxWidth > 800 ? 'حالة النظام' : 'الحالة',
                color: _getSystemStatusColorFromMap(routerInfo),
                iconSize: 28,
                valueSize: 24,
                titleSize: 16,
                spacing: 8,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildEnhancedStatItem({
    required IconData icon,
    required String value,
    required String title,
    required Color color,
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 12),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(icon, size: iconSize, color: color),
              SizedBox(width: 8),
              Text(
                value,
                style: TextStyle(
                  fontSize: valueSize,
                  fontWeight: FontWeight.bold,
                  color: color,
                  fontFamily: 'Tajawal',
                ),
              ),
            ],
          ),
          SizedBox(height: spacing),
          Text(
            title,
            style: TextStyle(
              color: Colors.white.withOpacity(0.9),
              fontSize: titleSize,
              fontFamily: 'Tajawal',
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildModernStatCard({
    required IconData icon,
    required String value,
    required String title,
    required Color color,
    required Gradient gradient,
    bool isSmall = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 2), // تقليل الهوامش
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(8), // تقليل نصف القطر
        gradient: gradient,
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min, // مهم للتحكم في الارتفاع
          children: [
            Container(
              padding: const EdgeInsets.all(6), // تصغير حجم الأيقونة
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                shape: BoxShape.circle,
              ),
              child: Icon(
                icon,
                size: isSmall ? 18 : 22, // ضبط حجم الأيقونة
                color: Colors.white,
              ),
            ),
            SizedBox(height: 4),
            Text(
              value,
              style: TextStyle(
                fontSize: isSmall ? 16 : 20, // ضبط حجم النص
                fontWeight: FontWeight.bold,
                color: Colors.white,
                fontFamily: 'Tajawal',
              ),
            ),
            SizedBox(height: 2),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.9),
                fontSize: isSmall ? 10 : 12, // ضبط حجم النص
                fontWeight: FontWeight.w500,
              ),
              textAlign: TextAlign.center,
              maxLines: 1, // منع التقسيم إلى سطور متعددة
              overflow: TextOverflow.ellipsis, // إضافة ... إذا طال النص
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVerticalStatsLayout({
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
    required Map<String, dynamic> routerInfo,
    required BoxConstraints constraints,
  }) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(16),
        color: _cardColor,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 10,
            spreadRadius: 2,
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(8),
        child: Row(
          children: [
            // جعل كل جزء يأخذ نفس المساحة
            Expanded(
              flex: 1,
              child: _buildModernStatCard(
                icon: Icons.people_alt_outlined,
                value: _activeHotspotUsersCountNotifier.value.toString(),
                title:
                    constraints.maxWidth > 800
                        ? 'المستخدمون النشطون'
                        : 'النشطون',
                color: Colors.green,
                gradient: LinearGradient(
                  colors: [Colors.green.shade400, Colors.green.shade700],
                ),
                isSmall: true,
              ),
            ),
            Container(
              height: 40,
              width: 1,
              margin: EdgeInsets.symmetric(vertical: 12),
              color: Colors.white.withOpacity(0.2),
            ),
            Expanded(
              flex: 1,
              child: _buildModernStatCard(
                icon: Icons.devices_other,
                value: _connectedDevicesCountNotifier.value.toString(),
                title: constraints.maxWidth > 800 ? 'اجهزة البث' : 'الأبراج',
                color: Colors.blueAccent,
                gradient: LinearGradient(
                  colors: [
                    Colors.blueAccent.shade400,
                    Colors.blueAccent.shade700,
                  ],
                ),
                isSmall: true,
              ),
            ),
            Container(
              height: 40,
              width: 1,
              margin: EdgeInsets.symmetric(vertical: 12),
              color: Colors.white.withOpacity(0.2),
            ),
            Expanded(
              flex: 1,
              child: _buildModernStatCard(
                icon: Icons.health_and_safety,
                value: _getSystemStatusFromMap(routerInfo),
                title: constraints.maxWidth > 800 ? 'حالة النظام' : 'الحالة',
                color: _getSystemStatusColorFromMap(routerInfo),
                gradient: LinearGradient(
                  colors: [
                    _getSystemStatusColorFromMap(routerInfo).withOpacity(0.8),
                    _getSystemStatusColorFromMap(routerInfo),
                  ],
                ),
                isSmall: true,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildAdaptiveStatItem({
    required IconData icon,
    required String value,
    required String title,
    required Color color,
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
  }) {
    return Flexible(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(icon, size: iconSize, color: color),
          SizedBox(height: spacing),
          Text(
            value,
            style: TextStyle(
              fontFamily: 'Tajawal',
              fontSize: valueSize,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: spacing / 2),
          Text(
            title,
            style: TextStyle(
              fontFamily: 'Tajawal',
              color: Colors.white.withOpacity(0.7),
              fontSize: titleSize,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard({
    required String title,
    required ValueNotifier value,
    required IconData icon,
    required Color color,
    bool isSystemStatus = false,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 6,
            spreadRadius: 2,
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: ValueListenableBuilder(
          valueListenable: value,
          builder:
              (context, val, _) => Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: color.withOpacity(0.1),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(icon, size: 24, color: color),
                  ),
                  const SizedBox(height: 10),
                  Text(
                    isSystemStatus
                        ? _getSystemStatusFromMap(val as Map<String, dynamic>)
                        : val.toString(),
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color:
                          isSystemStatus
                              ? _getSystemStatusColorFromMap(val)
                              : color,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    title,
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 14,
                    ),
                  ),
                ],
              ),
        ),
      ),
    );
  }

  Widget _buildCpuUsageCard() {
    return Container(
      height: 320,
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
      ),
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              const Icon(Icons.speed, color: Colors.blue),
              const SizedBox(width: 8),
              ValueListenableBuilder<Map<String, dynamic>>(
                valueListenable: _routerInfoNotifier,
                builder: (context, value, _) {
                  final cpuType = value['cpu']?.toString() ?? 'غير معروف';
                  return Expanded(
                    child: Row(
                      children: [
                        Text(
                          'استخدام المعالج',
                          style: TextStyle(
                            color: _textColor,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Tajawal',
                          ),
                        ),
                        const Spacer(),
                        Text(
                          cpuType,
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.7),
                            fontSize: 14,
                          ),
                        ),
                      ],
                    ),
                  );
                },
              ),
            ],
          ),
          const SizedBox(height: 20),
          ValueListenableBuilder<Map<String, dynamic>>(
            valueListenable: _routerInfoNotifier,
            builder: (context, value, _) {
              final cpuLoad =
                  double.tryParse(value['cpu-load']?.toString() ?? '0') ?? 0;
              final cpuColor = _getCpuColor(cpuLoad);

              return Column(
                children: [
                  Stack(
                    alignment: Alignment.center,
                    children: [
                      SizedBox(
                        width: 180,
                        height: 180,
                        child: CircularProgressIndicator(
                          value: cpuLoad / 100,
                          strokeWidth: 12,
                          backgroundColor: Colors.grey.withOpacity(0.2),
                          valueColor: AlwaysStoppedAnimation<Color>(cpuColor),
                        ),
                      ),
                      Column(
                        children: [
                          Text(
                            '${cpuLoad.toStringAsFixed(1)}%',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              fontSize: 32,
                              fontWeight: FontWeight.bold,
                              color: cpuColor,
                            ),
                          ),
                          Text(
                            'حمل المعالج',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor.withOpacity(0.7),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      _buildStatusIndicator(
                        'طبيعي',
                        Colors.green,
                        cpuLoad <= 70,
                      ),
                      const SizedBox(width: 16),
                      _buildStatusIndicator(
                        'تحذير',
                        Colors.orange,
                        cpuLoad > 70 && cpuLoad <= 90,
                      ),
                      const SizedBox(width: 16),
                      _buildStatusIndicator('حرج', Colors.red, cpuLoad > 90),
                    ],
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildMemoryUsageCard() {
    return Container(
      height: 320,
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
      ),
      padding: const EdgeInsets.all(14),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.memory, color: Colors.purple),
              const SizedBox(width: 8),
              Text(
                'استخدام الذاكرة',
                style: TextStyle(
                  color: _textColor,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Tajawal',
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          ValueListenableBuilder(
            valueListenable: _routerInfoNotifier,
            builder: (context, value, _) {
              // التحقق من وجود بيانات الذاكرة
              final hasMemoryData =
                  value.containsKey('free-memory') &&
                  value.containsKey('total-memory');

              // دالة مساعدة لتحويل القيمة إلى double بأمان
              double safeConvert(dynamic value) {
                if (value == null) return 0.0;
                if (value is num) return value.toDouble();
                if (value is String) {
                  return double.tryParse(value) ?? 0.0;
                }
                return 0.0;
              }

              final freeMem =
                  hasMemoryData ? safeConvert(value['free-memory']) : 0.0;
              final totalMem =
                  hasMemoryData ? safeConvert(value['total-memory']) : 1.0;

              // إذا لم يتم جلب البيانات بعد، نعرض 0%
              final usedPercent =
                  hasMemoryData
                      ? ((totalMem - freeMem) / totalMem * 100).toStringAsFixed(
                        1,
                      )
                      : '0.0';
              final usedValue =
                  hasMemoryData ? (totalMem - freeMem) / totalMem : 0.0;

              return Column(
                children: [
                  Stack(
                    alignment: Alignment.center,
                    children: [
                      SizedBox(
                        width: 175,
                        height: 175,
                        child: CircularProgressIndicator(
                          value: usedValue,
                          strokeWidth: 12,
                          backgroundColor: Colors.grey.withOpacity(0.2),
                          valueColor: AlwaysStoppedAnimation<Color>(
                            _getMemoryColor(usedValue * 100),
                          ),
                        ),
                      ),
                      Column(
                        children: [
                          Text(
                            '$usedPercent%',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              fontSize: 32,
                              fontWeight: FontWeight.bold,
                              color: _getMemoryColor(usedValue * 100),
                            ),
                          ),
                          Text(
                            'الذاكرة المستخدمة',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white.withOpacity(0.7),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceAround,
                    children: [
                      _buildMemoryDetail(
                        'الإجمالي',
                        hasMemoryData
                            ? _formatBytes(totalMem)
                            : 'جاري التحميل...',
                      ),
                      _buildMemoryDetail(
                        'المستخدم',
                        hasMemoryData
                            ? _formatBytes(totalMem - freeMem)
                            : 'جاري التحميل...',
                      ),
                      _buildMemoryDetail(
                        'المتاح',
                        hasMemoryData
                            ? _formatBytes(freeMem)
                            : 'جاري التحميل...',
                      ),
                    ],
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildStatusIndicator(String label, Color color, bool isActive) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        Container(
          width: 12,
          height: 12,
          decoration: BoxDecoration(
            color: isActive ? color : Colors.grey.withOpacity(0.3),
            shape: BoxShape.circle,
          ),
        ),
        const SizedBox(width: 4),
        Text(
          label,
          style: TextStyle(
            color: isActive ? color : Colors.grey,
            fontSize: 13,
            fontFamily: 'Tajawal',
          ),
        ),
      ],
    );
  }

  Widget _buildMemoryDetail(String title, String value) {
    return Column(
      children: [
        Text(
          title,
          style: TextStyle(
            color: Colors.white.withOpacity(0.7),
            fontSize: 12,
            fontFamily: 'Tajawal',
          ),
        ),
        const SizedBox(height: 4),
        Text(
          value,
          style: TextStyle(
            color: Colors.white,
            fontWeight: FontWeight.bold,
            fontFamily: 'Tajawal',
          ),
        ),
      ],
    );
  }

  Color _getCpuColor(double value) {
    if (value > 90) return Colors.red;
    if (value > 70) return Colors.orange;
    return Colors.green;
  }

  Color _getMemoryColor(double value) {
    if (value > 90) return Colors.red;
    if (value > 70) return Colors.orange;
    return Colors.blue;
  }

  String _getSystemStatusFromMap(Map<String, dynamic> info) {
    final cpuLoad = double.tryParse(info['cpu-load']?.toString() ?? '0') ?? 0;
    if (cpuLoad > 90) return 'حرج';
    if (cpuLoad > 70) return 'تحذير';
    return 'طبيعي';
  }

  Color _getSystemStatusColorFromMap(Map<String, dynamic> info) {
    switch (_getSystemStatusFromMap(info)) {
      case 'حرج':
        return Colors.red;
      case 'تحذير':
        return Colors.orange;
      default:
        return Colors.green;
    }
  }

  String _formatUptime(String? uptime) {
    if (uptime == null) return 'غير معروف';
    try {
      final seconds = int.parse(uptime);
      final days = seconds ~/ (24 * 3600);
      final hours = (seconds % (24 * 3600)) ~/ 3600;
      final minutes = (seconds % 3600) ~/ 60;
      if (days > 0) return '${days} يوم ${hours} ساعة';
      if (hours > 0) return '${hours} ساعة ${minutes} دقيقة';
      return '${minutes} دقيقة';
    } catch (e) {
      return uptime;
    }
  }

  String _formatBytes(double bytes) {
    if (bytes < 1024) return '${bytes.toStringAsFixed(0)} B';
    if (bytes < 1024 * 1024) return '${(bytes / 1024).toStringAsFixed(1)} KB';
    if (bytes < 1024 * 1024 * 1024)
      return '${(bytes / (1024 * 1024)).toStringAsFixed(1)} MB';
    return '${(bytes / (1024 * 1024 * 1024)).toStringAsFixed(1)} GB';
  }
}

// دالة لتحويل وقت السيرفر إلى Duration
Duration _parseUptime(String uptime) {
  try {
    int hours = 0, minutes = 0, seconds = 0;

    final hourMatch = RegExp(r'(\d+)h').firstMatch(uptime);
    if (hourMatch != null) hours = int.parse(hourMatch.group(1)!);

    final minuteMatch = RegExp(r'(\d+)m').firstMatch(uptime);
    if (minuteMatch != null) minutes = int.parse(minuteMatch.group(1)!);

    final secondMatch = RegExp(r'(\d+)s').firstMatch(uptime);
    if (secondMatch != null) seconds = int.parse(secondMatch.group(1)!);

    return Duration(hours: hours, minutes: minutes, seconds: seconds);
  } catch (e) {
    return Duration.zero;
  }
}

// دالة لتنسيق Duration إلى نص
String _formatDuration(Duration duration) {
  final days = duration.inDays;
  final hours = duration.inHours.remainder(24);
  final minutes = duration.inMinutes.remainder(60);
  final seconds = duration.inSeconds.remainder(60);

  if (days > 0) {
    return '${days} يوم ${hours} ساعة';
  } else if (hours > 0) {
    return '${hours} ساعة ${minutes} دقيقة';
  } else if (minutes > 0) {
    return '${minutes} دقيقة ${seconds} ثانية';
  } else {
    return '${seconds} ثانية';
  }
}

// فئة State لإدارة المؤقت
class _UptimeState extends StatefulWidget {
  final Duration initialDuration;
  final Widget Function(BuildContext, Duration) builder;

  const _UptimeState({required this.initialDuration, required this.builder});

  @override
  __UptimeStateState createState() => __UptimeStateState();
}

class __UptimeStateState extends State<_UptimeState> {
  late Duration _currentDuration;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _currentDuration = widget.initialDuration;
    _startTimer();
  }

  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _currentDuration += const Duration(seconds: 1);
      });
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return widget.builder(context, _currentDuration);
  }
}

class MobileUptimeDrawerItem extends StatelessWidget {
  final String? uptime;
  final String? version;
  final String? boardName;

  const MobileUptimeDrawerItem({
    super.key,
    required this.uptime,
    this.version,
    this.boardName,
  });

  @override
  Widget build(BuildContext context) {
    final isUptimeAvailable = uptime != null && uptime!.isNotEmpty;
    final serverDuration =
        isUptimeAvailable ? _parseUptime(uptime!) : Duration.zero;

    return Container(
      width: double.infinity, // تأخذ العرض الكامل
      padding: const EdgeInsets.all(12), // تقليل الحشو
      constraints: BoxConstraints(
        maxHeight: 102, // ارتفاع أقصى ثابت
      ),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.05),
        border: Border(
          bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
        ),
        borderRadius: BorderRadius.circular(5),
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min, // لتجنب الخروج عن الإطار
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // محتوى مضغوط في صفين
          Expanded(
            child: _UptimeState(
              initialDuration: serverDuration,
              builder: (context, duration) {
                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    // الصف الأول: وقت التشغيل والإصدار
                    Row(
                      children: [
                        Icon(Icons.timer, size: 18, color: Colors.green),
                        const SizedBox(width: 8),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              "وقت التشغيل",
                              style: TextStyle(
                                color: Colors.white.withOpacity(0.7),
                                fontSize: 10,
                                fontFamily: 'Tajawal',
                              ),
                            ),
                            Text(
                              _formatDuration(duration),
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 12,
                                fontWeight: FontWeight.bold,
                                fontFamily: 'Tajawal',
                              ),
                            ),
                          ],
                        ),
                        const SizedBox(width: 10),
                        if (version != null) ...[
                          Icon(
                            Icons.system_update,
                            size: 18,
                            color: Colors.blue,
                          ),
                          const SizedBox(width: 8),
                          Flexible(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "الإصدار",
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.7),
                                    fontSize: 10,
                                    fontFamily: 'Tajawal',
                                  ),
                                ),
                                Text(
                                  version!,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Tajawal',
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ],
                    ),
                    const SizedBox(height: 5),

                    // الصف الثاني: نموذج الجهاز فقط
                    if (boardName != null) ...[
                      Row(
                        children: [
                          Icon(Icons.memory, size: 18, color: Colors.orange),
                          const SizedBox(width: 8),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  "نموذج الجهاز",
                                  style: TextStyle(
                                    color: Colors.white.withOpacity(0.7),
                                    fontSize: 10,
                                    fontFamily: 'Tajawal',
                                  ),
                                ),
                                Text(
                                  boardName!,
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                    fontFamily: 'Tajawal',
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ],
                  ],
                );
              },
            ),
          ),
        ],
      ),
    );
  }
}

class UptimeDisplay extends StatelessWidget {
  final String? uptime;
  final Color? iconColor;
  final Color? textColor;
  final double? iconSize;
  final double? fontSize;
  final String? version;
  final String? boardName;

  const UptimeDisplay({
    super.key,
    required this.uptime,
    this.iconColor,
    this.textColor,
    this.iconSize,
    this.fontSize,
    this.version,
    this.boardName,
    required bool isMobile,
  });

  @override
  Widget build(BuildContext context) {
    final isDesktop = MediaQuery.of(context).size.width > 800;

    if (!isDesktop) {
      return const SizedBox.shrink(); // إخفاء العنصر في وضع الهاتف
    }

    final theme = Theme.of(context);
    final isUptimeAvailable = uptime != null && uptime!.isNotEmpty;

    if (!isUptimeAvailable) {
      return Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        decoration: BoxDecoration(
          color: const Color.fromARGB(255, 35, 64, 109),
          borderRadius: BorderRadius.circular(5),
          border: Border.all(color: const Color.fromARGB(255, 209, 209, 209)),
        ),
        child: Column(
          children: [
            const SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.dashboard, color: Colors.white, size: 28),
                  const SizedBox(width: 10),
                  Text(
                    'Micro Panel',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 30),
            Row(
              children: [
                Icon(Icons.schedule, size: iconSize ?? 20, color: Colors.grey),
                const SizedBox(width: 10),
                Expanded(
                  child: Text(
                    "جاري جلب بيانات مدة التشغيل...",
                    style: TextStyle(
                      color: Colors.white.withOpacity(0.7),
                      fontSize: fontSize ?? 16,
                      fontWeight: FontWeight.w500,
                      fontFamily: 'Tajawal',
                    ),
                  ),
                ),
              ],
            ),
          ],
        ),
      );
    }

    final serverDuration = _parseUptime(uptime!);
    return _UptimeState(
      initialDuration: serverDuration,
      builder: (context, duration) {
        return Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          decoration: BoxDecoration(
            color: const Color.fromARGB(255, 35, 64, 109),
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(30),
              bottomRight: Radius.circular(30),
            ),
            border: Border(
              left: BorderSide(color: Color.fromARGB(255, 209, 209, 209)),
              right: BorderSide(color: Color.fromARGB(255, 209, 209, 209)),
              bottom: BorderSide(color: Color.fromARGB(255, 209, 209, 209)),
              top: BorderSide.none,
            ),
          ),
          child: Column(
            children: [
              const SizedBox(height: 15),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 16),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(Icons.dashboard, color: Colors.white, size: 28),
                    const SizedBox(width: 10),
                    Text(
                      'Micro Panel',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 30),
              Row(
                children: [
                  Icon(
                    Icons.schedule,
                    size: iconSize ?? 20,
                    color: iconColor ?? Colors.greenAccent,
                  ),
                  const SizedBox(width: 10),
                  Expanded(
                    child: Text(
                      "مدة التشغيل: ${_formatDuration(duration)}",
                      style: TextStyle(
                        color: textColor ?? Colors.white,
                        fontSize: fontSize ?? 14,
                        fontWeight: FontWeight.w500,
                        fontFamily: 'Tajawal',
                      ),
                    ),
                  ),
                ],
              ),
              if (version != null || boardName != null) ...[
                const SizedBox(height: 10),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Icon(
                      Icons.system_update_alt,
                      size: iconSize ?? 20,
                      color: iconColor ?? Colors.white,
                    ),
                    const SizedBox(width: 10),
                    Flexible(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          if (version != null)
                            Text(
                              "الإصدار: $version",
                              style: TextStyle(
                                color: textColor ?? Colors.white,
                                fontSize: (fontSize ?? 12) - 2,
                                fontFamily: 'Tajawal',
                              ),
                            ),
                          if (boardName != null)
                            Text(
                              "النموذج: $boardName",
                              style: TextStyle(
                                color: textColor ?? Colors.white,
                                fontSize: (fontSize ?? 12) - 2,
                                fontFamily: 'Tajawal',
                              ),
                            ),
                        ],
                      ),
                    ),
                  ],
                ),
              ],
            ],
          ),
        );
      },
    );
  }
}

class AppSession {
  static final AppSession _instance = AppSession._internal();
  factory AppSession() => _instance;
  AppSession._internal();

  RouterOSClient? client;
}

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