لماذا لا يتم عرض الجزء المسؤول عن عرض المستخدمون النشطون وحالة النظام واجهزة البث في اعلى الشاشة في وضع الهرض في شاشة الحاسوب
الكود
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() {
    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;
    print('stoped');
  }

  void _startTimers() {
    _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: () {
            _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),
              ),
            ).then((value) {
              _startTimers();
            });
          },
        ),
        const SizedBox(height: 20),
        const Divider(color: Colors.white24, height: 1),

        _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: 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<Map<String, dynamic>>(
                  valueListenable: _routerInfoNotifier,
                  builder: (context, value, _) {
                    final serverDuration = _parseUptime(value['uptime']);
                    return _UptimeState(
                      initialDuration: serverDuration,
                      builder: (context, duration) {
                        return Text(
                          'وقت التشغيل: ${_formatDuration(duration)}',
                          style: TextStyle(
                            color: Colors.white.withOpacity(0.8),
                          ),
                        );
                      },
                    );
                  },
                ),
              ],
            ),
          ),
          _buildDrawerItem(
            icon: Icons.dashboard,
            title: 'الرئيسية',
            onTap: () {},
          ),
          _buildDrawerItem(
            icon: Icons.people,
            title: 'المستخدمون',
            onTap: () {
              _cancelAllTimers();
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => UsersPage(client: widget.client),
                ),
              ).then((value) {
                _startTimers();
              });
            },
          ),
          _buildDrawerItem(
            icon: Icons.person_add,
            title: 'إضافة مستخدم',
            onTap: () {
              _cancelAllTimers();
              Navigator.pop(context);
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder:
                      (context) => AddHotspotCardsPage(client: widget.client),
                ),
              ).then((value) {
                _startTimers();
              });
            },
          ),
          const Divider(color: Colors.white24),

          _buildDrawerItem(
            icon: Icons.logout,
            title: 'تسجيل خروج',
            color: Colors.red,
            onTap: () {
              _cancelAllTimers();
              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() {
    // ارتفاع ثابت لجميع الشاشات
    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,
          ),
        ),
        SizedBox(height: 4),
        Text(
          title,
          style: TextStyle(
            color: Colors.white.withOpacity(0.9),
            fontSize: titleSize,
          ),
        ),
      ],
    );
  }

  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,
                ),
              ),
            ],
          ),
          SizedBox(height: spacing),
          Text(
            title,
            style: TextStyle(
              color: Colors.white.withOpacity(0.9),
              fontSize: titleSize,
            ),
          ),
        ],
      ),
    );
  }

  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,
              ),
            ),
            SizedBox(height: 2),
            Text(
              title,
              style: TextStyle(
                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(
              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';
  }
}

// دالة لتحويل وقت السيرفر إلى 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) {
  String twoDigits(int n) => n.toString().padLeft(2, '0');
  final hours = duration.inHours;
  final minutes = duration.inMinutes.remainder(60);
  final seconds = duration.inSeconds.remainder(60);

  return '${hours}h${twoDigits(minutes)}m${twoDigits(seconds)}s';
}

// فئة 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);
  }
}