لماذا لا يتوقف عن جلب هذا
 void _startTimers() {
    _uptimeTimer = Timer.periodic(Duration(milliseconds: 1300), (_) {
      _fetchUptime();
      print('router_Timer');
    });
    _cpuTimer = Timer.periodic(Duration(milliseconds: 2100), (_) {
      _fetchCpu();
      print('router_cpu');
    });
    _usersTimer = Timer.periodic(Duration(seconds: 10), (_) {
      _fetchActiveHotspotUsers();
      print('router_Active');
    });
    _fetchAllData();
  }
عند الانتقال الى واجهه اخرى 
الكود
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:router_os_client/router_os_client.dart';
import 'Login.dart';
import 'hotspotUserList.dart';
import 'AddHotspotUser.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;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration(seconds: 1), _startTimers);
  }

  @override
  void dispose() {
    _uptimeTimer?.cancel();
    _cpuTimer?.cancel();
    _memoryTimer?.cancel();
    _usersTimer?.cancel();
    _devicesTimer?.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;
  }

  void _startTimers() {
    _uptimeTimer = Timer.periodic(Duration(milliseconds: 1300), (_) {
      _fetchUptime();
      print('router_Timer');
    });
    _cpuTimer = Timer.periodic(Duration(milliseconds: 2100), (_) {
      _fetchCpu();
      print('router_cpu');
    });
    _usersTimer = Timer.periodic(Duration(seconds: 10), (_) {
      _fetchActiveHotspotUsers();
      print('router_Active');
    });
    _fetchAllData();
  }

  Future<void> _fetchAllData() async {
    await Future.wait([
      _fetchUptime(),
      Future.delayed(Duration(milliseconds: 450), () => _fetchCpu()),
      _fetchMemory(),
      Future.delayed(Duration(seconds: 1), () => _fetchActiveHotspotUsers()),
      Future.delayed(
        Duration(milliseconds: 1200),
        () => _fetchConnectedDevices(),
      ),
    ]);
    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']);
  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;
    try {
      final response = await widget.client.talk([
        '/ip/hotspot/active/print',
        '=.proplist=user',
      ]);

      if (response.isEmpty) {
        _activeHotspotUsersCountNotifier.value = 0;
        return;
      }

      int activeUsersCount = 0;
      for (var item in response) {
        if (item is Map && item.containsKey('user')) {
          activeUsersCount++;
        }
      }

      if (_lastKnownUserCount != activeUsersCount) {
        _lastKnownUserCount = activeUsersCount;
        _activeHotspotUsersCountNotifier.value = activeUsersCount;
      }
    } catch (e) {
      if (mounted) _handleError(e);
    } finally {
      _isFetchingUsers = false;
    }
  }

  Future<void> _fetchConnectedDevices() async {
    if (_isFetchingDevices) return;
    _isFetchingDevices = true;
    try {
      final response = await widget.client.talk(['/ip/neighbor/print']);
      final devices = response.where((device) => device is Map).toList();
      _connectedDevicesCountNotifier.value = devices.length;
    } catch (e) {
      if (mounted) _handleError(e);
    } finally {
      _isFetchingDevices = false;
    }
  }

  void _handleError(dynamic e) {
    if (!mounted) return;
    _hasErrorNotifier.value = true;
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('خطأ في جلب البيانات: ${e.toString()}'),
        backgroundColor: Colors.red,
      ),
    );
  }

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

    switch (index) {
      case 0:
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => RouterDetailsPage(client: widget.client),
          ),
        );
        break;
      case 1:
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => UsersPage(client: widget.client),
          ),
        );
        break;
      case 2:
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => AddHotspotCardsPage(client: widget.client),
          ),
        );
        break;
      case 3:
        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: [
                const SizedBox(height: 40),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Icon(Icons.router, color: _primaryColor, size: 28),
                      const SizedBox(width: 10),
                      Text(
                        'لوحة تحكم الراوتر',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 30),
                _buildDesktopNavigation(),
              ],
            ),
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    _backgroundColor.withOpacity(0.9),
                    _backgroundColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(16),
                child: Column(
                  children: [
                    _buildAdaptiveStatsCard(),
                    const SizedBox(height: 20),
                    Row(
                      children: [
                        Expanded(child: _buildCpuUsageCard()),
                        const SizedBox(width: 20),
                        Expanded(child: _buildMemoryUsageCard()),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopNavigation() {
    return Column(
      children: [
        _buildNavItem(
          icon: Icons.dashboard,
          title: 'الرئيسية',
          isActive: true,
          onTap: () {},
        ),
        _buildNavItem(
          icon: Icons.people,
          title: 'المستخدمون',
          isActive: false,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => UsersPage(client: widget.client),
              ),
            );
          },
        ),
        _buildNavItem(
          icon: Icons.person_add,
          title: 'إضافة مستخدم',
          isActive: false,
          onTap: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder:
                    (context) => AddHotspotCardsPage(client: widget.client),
              ),
            );
          },
        ),
        const SizedBox(height: 20),
        const Divider(color: Colors.white24, height: 1),
        const SizedBox(height: 20),
        _buildNavItem(
          icon: Icons.settings,
          title: 'الإعدادات',
          isActive: false,
          onTap: () {},
        ),
        _buildNavItem(
          icon: Icons.logout,
          title: 'تسجيل خروج',
          isActive: false,
          onTap: () {
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (context) => Login()),
            );
          },
        ),
      ],
    );
  }

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

  Widget _buildMobileLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      appBar: AppBar(
        title: Text(
          'لوحة تحكم الراوتر',
          style: TextStyle(color: _textColor, fontSize: 20),
        ),
        centerTitle: true,
        backgroundColor: _backgroundColor,
        elevation: 0,
        iconTheme: IconThemeData(color: _textColor),
      ),
      drawer: _buildMobileDrawer(),
      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 _buildMobileDrawer() {
    return Drawer(
      backgroundColor: _backgroundColor,
      child: ListView(
        padding: EdgeInsets.zero,
        children: [
          DrawerHeader(
            decoration: BoxDecoration(
              color: _primaryColor.withOpacity(0.1),
              border: Border(
                bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Icon(Icons.router, size: 40, color: _primaryColor),
                const SizedBox(height: 10),
                ValueListenableBuilder(
                  valueListenable: _routerInfoNotifier,
                  builder:
                      (context, value, _) => Text(
                        value['identity'] ?? 'RouterOS',
                        style: const TextStyle(
                          color: Colors.white,
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                ),
                const SizedBox(height: 5),
                ValueListenableBuilder(
                  valueListenable: _routerInfoNotifier,
                  builder:
                      (context, value, _) => Text(
                        'وقت التشغيل: ${_formatUptime(value['uptime'])}',
                        style: TextStyle(color: Colors.white.withOpacity(0.8)),
                      ),
                ),
              ],
            ),
          ),
          _buildDrawerItem(
            icon: Icons.dashboard,
            title: 'الرئيسية',
            onTap: () {},
          ),
          _buildDrawerItem(
            icon: Icons.people,
            title: 'المستخدمون',
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UsersPage(client: widget.client),
                ),
              );
            },
          ),
          _buildDrawerItem(
            icon: Icons.person_add,
            title: 'إضافة مستخدم',
            onTap: () {
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder:
                      (context) => AddHotspotCardsPage(client: widget.client),
                ),
              );
            },
          ),
          const Divider(color: Colors.white24),
          _buildDrawerItem(
            icon: Icons.settings,
            title: 'الإعدادات',
            onTap: () {},
          ),
          _buildDrawerItem(
            icon: Icons.logout,
            title: 'تسجيل خروج',
            color: Colors.red,
            onTap: () {
              Navigator.pop(context);
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(builder: (context) => Login()),
              );
            },
          ),
        ],
      ),
    );
  }

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

  Widget _buildAdaptiveStatsCard() {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isSmallScreen = constraints.maxWidth < 600;
        final isVerySmallScreen = constraints.maxWidth < 400;

        // تحديد الأبعاد بناء على حجم الشاشة
        final iconSize =
            isVerySmallScreen
                ? 20.0
                : isSmallScreen
                ? 22.0
                : 28.0;
        final valueSize =
            isVerySmallScreen
                ? 16.0
                : isSmallScreen
                ? 18.0
                : 22.0;
        final titleSize =
            isVerySmallScreen
                ? 10.0
                : isSmallScreen
                ? 12.0
                : 14.0;
        final cardPadding =
            isVerySmallScreen
                ? 12.0
                : isSmallScreen
                ? 16.0
                : 20.0;
        final innerSpacing = isVerySmallScreen ? 4.0 : 8.0;

        return Container(
          width: double.infinity,
          constraints: BoxConstraints(maxWidth: 800),
          decoration: BoxDecoration(
            color: _cardColor,
            borderRadius: BorderRadius.circular(16),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.15),
                blurRadius: 10,
                spreadRadius: 2,
              ),
            ],
          ),
          padding: EdgeInsets.all(cardPadding),
          child: ValueListenableBuilder(
            valueListenable: _routerInfoNotifier,
            builder: (context, routerInfo, _) {
              return isSmallScreen
                  ? _buildVerticalStatsLayout(
                    iconSize: iconSize,
                    valueSize: valueSize,
                    titleSize: titleSize,
                    spacing: innerSpacing,
                    routerInfo: routerInfo,
                  )
                  : _buildHorizontalStatsLayout(
                    iconSize: iconSize,
                    valueSize: valueSize,
                    titleSize: titleSize,
                    spacing: innerSpacing,
                    routerInfo: routerInfo,
                  );
            },
          ),
        );
      },
    );
  }

  Widget _buildHorizontalStatsLayout({
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
    required Map<String, dynamic> routerInfo,
  }) {
    return Container(
      width: double.infinity, // هذه السطر يضمن أن العرض 100%
      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(12), // تقليل الهوامش الداخلية قليلاً
        child: IntrinsicHeight(
          // هذه الـ Widget تجعل الارتفاع متساويًا
          child: Row(
            children: [
              Expanded(
                // استخدام Expanded لكل بطاقة
                child: _buildModernStatCard(
                  icon: Icons.people_alt_outlined,
                  value: _activeHotspotUsersCountNotifier.value.toString(),
                  title: 'المستخدمون النشطون',
                  color: Colors.green,
                  gradient: LinearGradient(
                    colors: [Colors.green.shade400, Colors.green.shade700],
                  ),
                ),
              ),
              Container(
                width: 1,
                margin: EdgeInsets.symmetric(vertical: 8),
                color: Colors.white.withOpacity(0.2),
              ),
              Expanded(
                child: _buildModernStatCard(
                  icon: Icons.devices_other,
                  value: _connectedDevicesCountNotifier.value.toString(),
                  title: 'الأجهزة المتصلة',
                  color: Colors.blueAccent,
                  gradient: LinearGradient(
                    colors: [
                      Colors.blueAccent.shade400,
                      Colors.blueAccent.shade700,
                    ],
                  ),
                ),
              ),
              Container(
                width: 1,
                margin: EdgeInsets.symmetric(vertical: 8),
                color: Colors.white.withOpacity(0.2),
              ),
              Expanded(
                child: _buildModernStatCard(
                  icon: Icons.health_and_safety,
                  value: _getSystemStatusFromMap(routerInfo),
                  title: 'حالة النظام',
                  color: _getSystemStatusColorFromMap(routerInfo),
                  gradient: LinearGradient(
                    colors: [
                      _getSystemStatusColorFromMap(routerInfo).withOpacity(0.8),
                      _getSystemStatusColorFromMap(routerInfo),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildModernStatCard({
    required IconData icon,
    required String value,
    required String title,
    required Color color,
    required Gradient gradient,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(
        horizontal: 4,
      ), // تقليل الهوامش الأفقية
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(12),
        gradient: gradient,
        boxShadow: [
          BoxShadow(
            color: color.withOpacity(0.2),
            blurRadius: 10,
            spreadRadius: 2,
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 8),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              padding: const EdgeInsets.all(10), // تصغير حجم الأيقونة قليلاً
              decoration: BoxDecoration(
                color: Colors.white.withOpacity(0.2),
                shape: BoxShape.circle,
              ),
              child: Icon(
                icon,
                size: 24,
                color: Colors.white,
              ), // تصغير حجم الأيقونة
            ),
            const SizedBox(height: 10),
            Text(
              value,
              style: const TextStyle(
                fontSize: 22, // تصغير حجم الخط قليلاً
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: TextStyle(
                color: Colors.white.withOpacity(0.9),
                fontSize: 13, // تصغير حجم الخط قليلاً
                fontWeight: FontWeight.w500,
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildVerticalStatsLayout({
    required double iconSize,
    required double valueSize,
    required double titleSize,
    required double spacing,
    required Map<String, dynamic> routerInfo,
  }) {
    return Column(
      children: [
        _buildEnhancedStatItem(
          icon: Icons.people_alt_outlined,
          value: _activeHotspotUsersCountNotifier.value.toString(),
          title: 'المستخدمون النشطون',
          color: Colors.green,
          iconSize: iconSize,
          valueSize: valueSize,
          titleSize: titleSize,
          spacing: spacing,
        ),
        Padding(
          padding: EdgeInsets.symmetric(vertical: spacing),
          child: Divider(color: Colors.white.withOpacity(0.2), height: 1),
        ),
        _buildEnhancedStatItem(
          icon: Icons.devices_other,
          value: _connectedDevicesCountNotifier.value.toString(),
          title: 'الأجهزة المتصلة',
          color: Colors.blueAccent,
          iconSize: iconSize,
          valueSize: valueSize,
          titleSize: titleSize,
          spacing: spacing,
        ),
        Padding(
          padding: EdgeInsets.symmetric(vertical: spacing),
          child: Divider(color: Colors.white.withOpacity(0.2), height: 1),
        ),
        _buildEnhancedStatItem(
          icon: Icons.health_and_safety,
          value: _getSystemStatusFromMap(routerInfo),
          title: 'حالة النظام',
          color: _getSystemStatusColorFromMap(routerInfo),
          iconSize: iconSize,
          valueSize: valueSize,
          titleSize: titleSize,
          spacing: spacing,
        ),
      ],
    );
  }

  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 Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Container(
          padding: EdgeInsets.all(spacing * 1.5),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
          child: Icon(icon, size: iconSize, color: color),
        ),
        SizedBox(height: spacing),
        Text(
          value,
          style: TextStyle(
            fontSize: valueSize,
            fontWeight: FontWeight.bold,
            color: color,
          ),
        ),
        SizedBox(height: spacing / 2),
        Text(
          title,
          style: TextStyle(
            color: Colors.white.withOpacity(0.8),
            fontSize: titleSize,
            height: 1.2,
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  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(
              fontSize: valueSize,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          SizedBox(height: spacing / 2),
          Text(
            title,
            style: TextStyle(
              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(
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                      color:
                          isSystemStatus
                              ? _getSystemStatusColorFromMap(val)
                              : color,
                    ),
                  ),
                  const SizedBox(height: 5),
                  Text(
                    title,
                    style: TextStyle(
                      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: [
              Icon(Icons.speed, color: Colors.blue),
              const SizedBox(width: 8),
              Text(
                'استخدام المعالج',
                style: TextStyle(
                  color: _textColor,
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          ValueListenableBuilder(
            valueListenable: _routerInfoNotifier,
            builder: (context, value, _) {
              final cpuLoad =
                  double.tryParse(value['cpu-load']?.toString() ?? '0') ?? 0;
              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>(
                            _getCpuColor(cpuLoad),
                          ),
                        ),
                      ),
                      Column(
                        children: [
                          Text(
                            '$cpuLoad%',
                            style: TextStyle(
                              fontSize: 32,
                              fontWeight: FontWeight.bold,
                              color: _getCpuColor(cpuLoad),
                            ),
                          ),
                          Text(
                            'حمل المعالج',
                            style: TextStyle(
                              color: Colors.white.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(16),
      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,
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),
          ValueListenableBuilder(
            valueListenable: _routerInfoNotifier,
            builder: (context, value, _) {
              final freeMem =
                  double.tryParse(value['free-memory']?.toString() ?? '0') ?? 0;
              final totalMem =
                  double.tryParse(value['total-memory']?.toString() ?? '1') ??
                  1;
              final usedPercent = ((totalMem - freeMem) / totalMem * 100)
                  .toStringAsFixed(1);
              final usedValue = (totalMem - freeMem) / totalMem;

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

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

  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';
  }
}