Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

ما الفرق بين ال tab bar في وضع الحاسوب ووضع الهاتف import 'dart:async'; import…

  1. User

    ما الفرق بين ال tab bar في وضع الحاسوب ووضع الهاتف import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart' as intl; import 'package:micro_panel/AddHotspotUser.dart'; import 'package:micro_panel/AddUserManagerUser.dart'; import 'package:micro_panel/HelpDesk.dart'; import 'package:micro_panel/HomePage.dart'; import 'package:micro_panel/Login.dart'; import 'package:micro_panel/SendNotes.dart'; import 'package:micro_panel/UserManagerProfile.dart'; import 'package:micro_panel/UserManagerReport.dart'; import 'package:micro_panel/UserManagerUserList.dart'; import 'package:micro_panel/hotspotUserList.dart'; import 'package:path_provider/path_provider.dart'; import 'package:router_os_client/router_os_client.dart'; import 'package:http/http.dart' as http; import 'package:flutter/services.dart';

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

    @override State createState() => _HotspotProfileState(); }

    class _HotspotProfileState extends State with SingleTickerProviderStateMixin { Color _primaryColor = const Color(0xFF3B82F6); Color _backgroundColor = const Color(0xFF0A192F); Color _cardColor = const Color(0xFF172A46); Color _textColor = Colors.white; late TabController _tabController; String _profileName = ''; String _downloadValue = ''; String _uploadValue = '';

    String _profileId = '';

    String _downloadSpeedUnit = 'كيلو'; String _uploadSpeedUnit = 'كيلو'; final TextEditingController downloadController = TextEditingController(); final TextEditingController uploadController = TextEditingController();

    final TextEditingController _feedbackController = TextEditingController(); final ValueNotifier _ratingNotifier = ValueNotifier(0); final ValueNotifier _feedbackTypeNotifier = ValueNotifier( 'suggestion', ); final ValueNotifier _isSendingNotifier = ValueNotifier(false); int _currentIndex = 0;

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

    @override void dispose() { _feedbackController.dispose(); _ratingNotifier.dispose(); _feedbackTypeNotifier.dispose(); _isSendingNotifier.dispose(); downloadController.dispose(); uploadController.dispose(); _tabController.dispose(); super.dispose(); }

    @override void initState() { super.initState(); _tabController = TabController(length: 2, vsync: this); _tabController.addListener(_handleTabSelection); }

    void _handleTabSelection() { if (_tabController.indexIsChanging) { setState(() {}); } }

    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.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => UsersPage(client: widget.client),
          ),
        );
        break;
      case 2:
        Navigator.pushReplacement(
          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: [ _buildDesktopNavigation(), Expanded( child: Column( children: [ Expanded( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ _backgroundColor.withOpacity(0.9), _backgroundColor.withOpacity(0.7), ], ), ), child: _buildMainContent(), ), ), ], ), ), ], ), ); }

    PreferredSizeWidget _buildAppBar(BuildContext context) { return AppBar( title: const Text( 'إضافة بروفايل', style: TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 17, ), ), backgroundColor: _backgroundColor, centerTitle: true, elevation: 0, leading: Builder( builder: (context) => IconButton( icon: Icon(Icons.menu_rounded, color: _textColor), onPressed: () => Scaffold.of(context).openDrawer(), ), ), ); }

    // تعديل دالة بناء واجهة الهاتف Widget _buildMobileLayout(BuildContext context) { return Scaffold( backgroundColor: _backgroundColor, drawer: _buildUniversalDrawer(), appBar: _buildAppBar(context), body: _buildMainContent(showHeader: false), ); }

    String _convertToRouterUnit(String unit) { if (unit == 'كيلو') return 'K'; if (unit == 'ميجا') return 'M'; return 'K'; // افتراضي }

    Widget _buildMainContent({bool showHeader = true}) { return Column( children: [ Container( height: 60,

          child: TabBar(
            controller: _tabController,
            indicatorColor: _primaryColor,
            indicatorWeight: 3,
            labelColor: _primaryColor,
            unselectedLabelColor: Colors.white.withOpacity(0.5),
            tabs: const [
              Tab(icon: Icon(Icons.speed_rounded), text: 'إضافة بروفايل'),
              Tab(icon: Icon(Icons.edit_note_rounded), text: 'تعديل بروفايل'),
            ],
          ),
        ),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: [_buildAddProfileTab(), _buildEditProfileTab()],
          ),
        ),
      ],
    );
    

    }

    Widget _buildAddProfileTab() { return SingleChildScrollView( padding: EdgeInsets.all(16), child: Column( children: [ SizedBox(height: 16), // حاوية خلفية للحقول Container( decoration: BoxDecoration( color: Colors.white.withOpacity(0.05), borderRadius: BorderRadius.circular(15), border: Border.all(color: Colors.white.withOpacity(0.1)), ), padding: EdgeInsets.all(16), child: Column( children: [ Text( 'إعدادات البروفايل', style: TextStyle( fontFamily: 'Tajawal', fontSize: 18, fontWeight: FontWeight.bold, color: _textColor, ), ), SizedBox(height: 16), // حقل إدخال لاسم البروفايل TextField( decoration: InputDecoration( labelText: 'اسم البروفايل', labelStyle: TextStyle( fontFamily: 'Tajawal', color: _textColor.withOpacity(0.8), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide( color: Colors.white.withOpacity(0.2), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide( color: Colors.white.withOpacity(0.2), ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: _primaryColor), ), contentPadding: EdgeInsets.symmetric( horizontal: 16, vertical: 14, ), fillColor: _cardColor, filled: true, ), style: TextStyle(fontFamily: 'Tajawal', color: textColor), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')), ], onChanged: (value) { setState(() { _profileName = value; }); }, ), SizedBox(height: 12),

                // حقل حد التحميل
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة التحميل',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _downloadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _downloadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _downloadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),
    
                SizedBox(height: 12),
    
                // حقل حد الرفع
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة الرفع',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _uploadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _uploadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _uploadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16),
    
                ElevatedButton(
                  onPressed: () async {
                    if (_profileName.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال اسم البروفايل'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
    
                    if (_downloadValue.isEmpty || _uploadValue.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال قيم السرعة'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
    
                    try {
                      final response = await widget.client.talk([
                        '/ip/hotspot/user/profile/add',
                        '=name=$_profileName',
                        '=rate-limit=${_downloadValue}${_convertToRouterUnit(_downloadSpeedUnit)}/${_uploadValue}${_convertToRouterUnit(_uploadSpeedUnit)}',
                      ]);
    
                      if (response.isNotEmpty) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('تم إنشاء البروفايل بنجاح'),
                            backgroundColor: Colors.green,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('حدث خطأ أثناء إنشاء البروفايل'),
                            backgroundColor: Colors.red,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      }
                    } catch (e) {
                      print('$e');
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('حدث خطأ اثناء انشاء البروفايل'),
                          backgroundColor: Colors.red,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      );
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _primaryColor,
                    foregroundColor: _textColor,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    minimumSize: const Size(double.infinity, 50),
                  ),
                  child: const Text('إضافة البروفايل'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
    

    }

    Widget _buildEditProfileTab() { return FutureBuilder<List<Map<String, dynamic>>>( future: _fetchProfiles(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return Center(child: Text('حدث خطأ في جلب البيانات')); } else if (!snapshot.hasData || snapshot.data!.isEmpty) { return Center(child: Text('لا يوجد بروفايلات متاحة')); }

        final profiles = snapshot.data!;
        return SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(15),
                  border: Border.all(color: Colors.white.withOpacity(0.1)),
                ),
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    Text(
                      'تعديل إعدادات البروفايل',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: _textColor,
                      ),
                    ),
                    SizedBox(height: 16),
    
                    // Dropdown لاختيار البروفايل
                    DropdownButtonFormField<String>(
                      value:
                          profiles.any((p) => p['name'] == _profileName)
                              ? _profileName
                              : null,
                      items:
                          profiles.map((profile) {
                            return DropdownMenuItem<String>(
                              value: profile['name'],
                              child: Text(
                                profile['name'],
                                style: TextStyle(color: _textColor),
                              ),
                            );
                          }).toList(),
                      onChanged: (String? selectedProfile) {
                        if (selectedProfile != null) {
                          _loadProfileData(selectedProfile);
                        }
                      },
                      decoration: InputDecoration(
                        labelText: 'اختر البروفايل للتعديل',
                        labelStyle: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.8),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: _primaryColor),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 14,
                        ),
                        fillColor: _cardColor,
                        filled: true,
                      ),
                      dropdownColor: _cardColor,
                      style: TextStyle(color: _textColor),
                    ),
                    SizedBox(height: 12),
    
                    // حقل حد التحميل
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: downloadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة التحميل',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _downloadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _downloadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
    
                    SizedBox(height: 12),
    
                    // حقل حد الرفع
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: uploadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة الرفع',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _uploadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _uploadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 16),
    
                    ElevatedButton(
                      onPressed: _updateProfile,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        foregroundColor: _textColor,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      child: const Text('تحديث البروفايل'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
    

    }

    Future _loadProfileData(String profileName) async { try { final response = await widget.client.talk([ '/ip/hotspot/user/profile/print', '?name=$profileName', ]);

      if (response.isNotEmpty) {
        final profile = response.first;
        final rateLimit = profile['rate-limit']?.split('/') ?? ['', ''];
    
        // تحليل قيمة rate-limit
        String downloadValue = '';
        String uploadValue = '';
        String downloadUnit = 'كيلو';
        String uploadUnit = 'كيلو';
    
        if (rateLimit.length == 2) {
          // تحليل سرعة التحميل
          if (rateLimit[0].contains('M')) {
            downloadValue = rateLimit[0].replaceAll('M', '');
            downloadUnit = 'ميجا';
          } else if (rateLimit[0].contains('K')) {
            downloadValue = rateLimit[0].replaceAll('K', '');
            downloadUnit = 'كيلو';
          }
    
          // تحليل سرعة الرفع
          if (rateLimit[1].contains('M')) {
            uploadValue = rateLimit[1].replaceAll('M', '');
            uploadUnit = 'ميجا';
          } else if (rateLimit[1].contains('K')) {
            uploadValue = rateLimit[1].replaceAll('K', '');
            uploadUnit = 'كيلو';
          }
        }
    
        setState(() {
          _profileName = profileName;
          _profileId = profile['.id'] ?? ''; // حفظ معرف البروفايل
          downloadController.text = downloadValue;
          uploadController.text = uploadValue;
          _downloadSpeedUnit = downloadUnit;
          _uploadSpeedUnit = uploadUnit;
        });
      }
    } catch (e) {
      print('Error loading profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحميل بيانات البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
    

    }

    Future _updateProfile() async { if (_profileName.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('الرجاء اختيار بروفايل للتعديل'), backgroundColor: Colors.red, ), ); return; }

    if (downloadController.text.isEmpty || uploadController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('الرجاء إدخال قيم السرعة'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }
    
    try {
      final command = [
        '/ip/hotspot/user/profile/set',
        '=.id=$_profileId',
        '=rate-limit=${downloadController.text}${_convertToRouterUnit(_downloadSpeedUnit)}/${uploadController.text}${_convertToRouterUnit(_uploadSpeedUnit)}',
      ];
    
      final response = await widget.client.talk(command);
    
      if (response.isEmpty ||
          !response.any((reply) => reply.containsKey('!trap'))) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم تحديث البروفايل بنجاح'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('حدث خطأ أثناء تحديث البروفايل'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      print('Error updating profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحديث البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
    

    }

    Future<List<Map<String, dynamic>>> _fetchProfiles() async { try { final response = await widget.client.talk([ '/ip/hotspot/user/profile/print', '=.proplist=name,rate-limit,.id', ]);

      final uniqueProfiles = <Map<String, dynamic>>[];
      final names = <String>{};
    
      for (var profile in response) {
        if (!names.contains(profile['name'])) {
          names.add(profile['name']!);
          uniqueProfiles.add({
            'name': profile['name'],
            'rate-limit': profile['rate-limit'],
            '.id': profile['.id'],
          });
        }
      }
    
      return uniqueProfiles;
    } catch (e) {
      debugPrint('Error fetching profiles: $e');
      return [];
    }
    

    }

    Widget _buildDesktopNavigation() { return SingleChildScrollView( child: Container( width: 280, height: MediaQuery.of(context).size.height, decoration: BoxDecoration( color: Colors.white.withOpacity(0.05), border: Border( right: BorderSide(color: Colors.white.withOpacity(0.1)), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 30), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ Icon(Icons.speed, color: _primaryColor, size: 28), const SizedBox(width: 10), Text( 'إضافة بروفايل', style: TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), ], ), ), const SizedBox(height: 30), Expanded( 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: false, onTap: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => RouterDetailsPage(client: widget.client), ), ); }, ),

                    // قسم الهوتسبوت (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة الهوتسبوت',
                      icon: Icons.wifi,
                      initiallyExpanded: isHotspotExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHotspotExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        UsersPage(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: true,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.person_add,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.group_add,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),
    
                    // قسم اليوزر مانجر (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة اليوزر مانجر',
                      icon: Icons.manage_accounts,
                      initiallyExpanded: isUserManagerExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isUserManagerExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people_outline,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => UserManagerUserList(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => UserManagerProfile(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.payment_rounded,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.credit_score,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
    
                        _buildNavItem(
                          icon: Icons.assignment,
                          title: 'السجلات',
                          isActive: false,
                          onTap: () {
                            // Navigation code here
                          },
                        ),
                      ],
                    ),
    
                    // قسم الإعدادات والأدوات (قابل للطي)
                    _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: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => HelpDesk(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.feedback,
                          title: 'إرسال ملاحظات',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => SendNotes(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.info_outline,
                          title: 'حول التطبيق',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.logout,
                          title: 'تسجيل الخروج',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (context) => Login()),
                            );
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
    

    }

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

    Widget _buildExpandableSection({ required String title, required IconData icon, required List children, required bool initiallyExpanded, required ValueChanged 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 _buildUniversalDrawer() { return Drawer( backgroundColor: _backgroundColor, child: SafeArea( child: ListView( padding: EdgeInsets.zero, children: [ SizedBox( height: 70, child: DrawerHeader( decoration: BoxDecoration( color: _primaryColor.withOpacity(0.1), border: Border( bottom: BorderSide(color: Colors.white.withOpacity(0.1)), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.network_check, size: 30, color: Colors.white, ), const SizedBox(width: 8), Text( 'Micro Panel', style: const TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold, ), ), ], ), ], ), ), ),

            // Main Navigation Items
            _buildUniversalDrawerItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) =>
                            RouterDetailsPage(client: widget.client),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
    
            // Hotspot Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة الهوتسبوت',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              initiallyExpanded: true,
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UsersPage(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'البروفايل',
                  onTap: () {},
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.person_add,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.group_add,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),
    
            // User Manager Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(
                    Icons.manage_accounts,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة اليوزر مانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
    
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people_outline,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerUserList(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.speed,
                  title: 'البروفايل',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerProfile(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.payment_rounded,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.credit_score,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerSession(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),
    
            // Settings Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'الإعدادات والأدوات',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.settings,
                  title: 'إعدادات النظام',
                  onTap: () {
                    // 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: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                HelpDesk(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                SendNotes(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),
    
            const Divider(color: Colors.white24),
    
            // Logout Item
            _buildUniversalDrawerItem(
              icon: Icons.logout,
              title: 'تسجيل خروج',
              color: Colors.red,
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) => Login(),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
    

    }

    Widget _buildUniversalDrawerItem({ required IconData icon, required String title, Color color = Colors.white, required VoidCallback onTap, }) { return ListTile( leading: Icon(icon, color: color), title: Text( title, style: TextStyle(fontFamily: 'Tajawal', color: color, fontSize: 14), ), onTap: onTap, contentPadding: const EdgeInsets.symmetric(horizontal: 16), ); }

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

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

  2. Assistant

    الفرق بين TabBar في وضع الحاسوب (Desktop) ووضع الهاتف (Mobile) في الكود الذي قدمته يعتمد بشكل أساسي على كيفية تنظيم واجهة المستخدم (Layout) والتفاعل مع التنقل في التطبيق:


    1. في وضع الحاسوب (Desktop):

    • لا تستخدم TabBar في AppBar أو أسفل الشاشة، وإنما ضمن المحتوى الرئيسي فقط
    • تبويب المحتوى يتم ضمن جزء من الشاشة الواسعة، حيث الواجهة مقسمة إلى قسم جانبي (Navigation Sidebar) وقسم المحتوى الرئيسي.
    • التنقل الأساسي بين صفحات التطبيق يتم عبر القائمة الجانبية الجانبية (Sidebar) التي تحتوي على قائمة مرنة وقابلة للطي.
    • يتم عرض التبويبات (TabBar) داخل المحتوى الرئيسي (داخل عمود في الرصف الرئيسي Row)، وليس بشكل دائم في أعلى الشاشة أو أسفلها، بل في موقع ثابت بمحاذاة المحتوى.
    • التفاعل مع التنقل والصفحات يتم من خلال النقر على عناصر التنقل في الشريط الجانبي وليس عبر تبويبات في أسفل الشاشة.

    2. في وضع الهاتف (Mobile):

    • يتم عرض واجهة أبسط وأكثر تركيزًا على المحتوى.
    • TabBar يعود ليكون في الجسم الرئيسي (Body) أسفل الـ AppBar أو في أعلى صفحة المحتوى.
    • يستخدم التنقل عبر الـ drawer (الشريط الجانبي القابل للسحب) و TabBar في الصفحة نفسها.
    • TabBar هنا يظهر كمكون مرئي رئيسي مع أيقونات ونصوص للتنقل بين التبويبات، وتكون التبويبات متاحة مباشرة للمستخدم.
    • لا تستخدم قائمة جانبية دائمة كما في نسخة سطح المكتب، وإنما تستخدم Drawer.

    ملخص الفرق والترتيب في التطبيق:

    النقطةالوضع على الحاسوب (Desktop)الوضع على الهاتف (Mobile)
    مكان التنقل الأساسيشريط جانبي (Sidebar) دائم وثابتDrawer (قائمة جانبية قابلة للسحب)
    تنظيم تبويبات TabBarTabBar داخل الجزء الرئيسي من المحتوىTabBar مرئي في شاشة المحتوى مع AppBar
    هل الـ TabBar ثابت في الشاشة؟لا، فقط في داخل محتوى الصفحة وليس في أعلى/أسفل الشاشةنعم، ظاهر ضمن المحتوى بشكل واضح
    تجربة المستخدمالتنقل عبر القائمة مع إمكانية طي وتوسيعالتنقل عبر التبويبات مباشرة أو عبر Drawer
    تعدد وتوزيع المحتوىتقسيم الشاشة لجزئين (قائمة جانبية + محتوى)شاشة واحدة بسيطة مع واجهة تبويبات وعناصر مرئية أقل

    في كود Flutter الخاص بك:

    • في دالة build:

      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);
              }
            },
          ),
        );
      }
      
      • يتم التمييز بين الحاسوب والهاتف عبر عرض الشاشة.
      • في حال كانت الشاشة عريضة (أكثر من 800 بكسل)، يعرض الواجهة الخاصة بالحاسوب _buildDesktopLayout.
      • في حال كانت الشاشة ضيقة (الهاتف)، يعرض _buildMobileLayout.
    • في الهاتف يتم عرض:

      • Scaffold مع AppBar.
      • Drawer.
      • الـ TabBar مع التبويبات داخل الجسم.
    • في الحاسوب يتم عرض:

      • Scaffold مع صف (Row) فيه القائمة الجانبية والعمود المحتوي على TabBar.
      • لا يوجد Drawer ولا AppBar يحتوي TabBar.

    خلاصة:

    • TabBar في الهاتف: يكون جزءًا من الجسم مع header بسيط في الأعلى، ويتيح تغيير تبويبات داخل نفس الصفحة.
    • TabBar في الحاسوب: يستخدم داخل القسم الرئيسي فقط، والتنقل بين الصفحات يتحكم به الـ Sidebar وليس TabBar أعلى أو أسفل.

    إذا أردت تحسين أو توضيح أي نقطة أخرى تخص التبويبات أو التصميم متجاوب مع الهاتف والحاسوب الرجاء إخباري!

  3. User

    اريد ان يكون اسلوب جلب البيانات في وضع الهاتف والحاسوب بنفس الطريقة

  4. Assistant

    لفهم طلبك: تريد أن يكون أسلوب جلب البيانات (fetching data) وإظهارها سواء في وضع الهاتف (Mobile) أو وضع الحاسوب (Desktop) موحدًا بنفس الطريقة، أي أن تطبيقك يعرض ويحدث البيانات بنفس المنطق وأسلوب العرض سواء في الهاتف أو الحاسوب.

    في الكود الذي قدمته:

    • لديك في كلا الوضعين (الهاتف والحاسوب) عنصر رئيسي مشترك وهو TabBar مع TabBarView لعرض التبويبات.
    • الدالة _buildMainContent() هي التي تبني محتوى الـ TabBar والتبويبات (AddProfile & EditProfile).
    • في الواجهة الخاصة بالهاتف وكذلك الحاسوب، هذه الدالة تستخدم بنفس الطريقة.

    الحل: توحيد جلب البيانات إلى داخل _buildMainContent وعدم تكرارها في أماكن مختلفة

    خطوات لتوحيد الطريقة واستخدام نفس أسلوب جلب البيانات في الهاتف والحاسوب:

    1. جعل جلب البيانات (والمستقبل Future) داخل التبويب نفسه (مثلاً الـ EditProfileTab).

      وهذا ما تقوم به بالفعل في دالة _buildEditProfileTab():

      Widget _buildEditProfileTab() {
        return FutureBuilder<List<Map<String, dynamic>>>(
          future: _fetchProfiles(), // هنا جلب البيانات
          builder: (context, snapshot) {
            // بناء الواجهة بناءً على حالة الجلب
            ...
          },
        );
      }
      
    2. التأكد أن هذه الدالة _buildEditProfileTab() تُستخدم في TabBarView في كلا الوضعين Mobile و Desktop:

      في دالة _buildMainContent() لديك:

      Widget _buildMainContent({bool showHeader = true}) {
        return Column(
          children: [
            Container(
              height: 60,
              child: TabBar(
                 controller: _tabController,
                 ...,
                 tabs: const [
                   Tab(icon: Icon(Icons.speed_rounded), text: 'إضافة بروفايل'),
                   Tab(icon: Icon(Icons.edit_note_rounded), text: 'تعديل بروفايل'),
                 ],
              ),
            ),
            Expanded(
              child: TabBarView(
                controller: _tabController,
                children: [_buildAddProfileTab(), _buildEditProfileTab()],
              ),
            ),
          ],
        );
      }
      

      في المستدعي (بناء الواجهة Desktop و Mobile) تستخدم:

      • في Desktop داخل _buildDesktopLayout, ضمن Expanded(child: Container(child: _buildMainContent()))
      • في Mobile داخل body: _buildMainContent(showHeader: false)
    3. التأكد من أن البيانات تنعكس وتتحدث في كلا الوضعين بنفس الطريقة

      • تحدث بنفس الـ setState() وعدم استخدام طرق مختلفة لجلب أو تحديث البيانات.
      • استخدام نفس المتغيرات controllers والقيم في كلا الوضعين.
    4. عدم تكرار جلب البيانات في مكانين مختلفين، أو عدم عمل FutureBuilder في مكانين مختلفين


    نصيحة عملية وشائعة:

    • استخدم دالة واحدة لجلب البيانات وهي _fetchProfiles() داخل دالة _buildEditProfileTab() مع FutureBuilder كما هو موجود.
    • لا تستخدم FutureBuilder في _buildDesktopNavigation أو أماكن أخرى.
    • دع الواجهة فقط تبني حسب حالة FutureBuilder.
    • استخدم محددات حجم الشاشة فقط لتغيير التصميم (Layout) لا لتغيير طريقة جلب البيانات.

    تعديل بسيط للتأكيد على توحيد أسلوب جلب البيانات والتعامل معها:

    • محتوى التبويبات متطابق في الهاتف والحاسوب (كما لديك الآن).
    • إذا كانت هناك اختلافات في أماكن عرض البيانات، تأكد من فصل واجهة المستخدم عن المنطق (البيانات).

    إضافيًا: اقتراح تحسين بسيط

    • استخدم مثلاً ChangeNotifier أو Provider أو Riverpod لإدارة الحالة بحيث يتم تحميل البيانات مرة واحدة ويعاد استخدامها بأي مكان في التطبيق، سواء في الهاتف أو الحاسوب.
    • لكن إن أردت الطريقة البسيطة الحالية: استمر على FutureBuilder في _buildEditProfileTab() داخل محتوى التبويب.

    خلاصة

    لجعل أسلوب جلب البيانات موحد:

    • اجعل جلب البيانات يتم فقط داخل التبويبات (داخل _buildEditProfileTab) عبر FutureBuilder.
    • استدعِ هذه التبويبات في كلا الوضعين (Desktop و Mobile) بنفس الطريقة دون تغيير كود الجلب أو بدء Future مختلف.
    • لا تغير في منطق البيانات بناءً على حجم الشاشة، فقط غيّر طريقة عرض الواجهات.

    إذا تريد، يمكنني مساعدتك بتعديل الكود بحيث يكون تطبيقًا عمليًا أكثر في هذا الجانب. فقط أخبرني!

  5. User

    لكن لماذا عند العرض في مقاس شاشة الهاتف عند الانتقال الى قسم تعديل البروفايل لا يحدث مشاكل اما في وضع شاشة الهاتف تحدث مشاكل عند الانتقال الى قسم تعديل البروفايل ما السبب

  6. Assistant

    شكرًا لتوضيح المشكلة. من وصفك:

    • في وضع الهاتف (الشاشة الضيقة): عند الانتقال إلى قسم "تعديل البروفايل" لا تحدث مشاكل (أي كل شيء يعمل كما هو متوقع).
    • في وضع الحاسوب (الشاشة العريضة): عند الانتقال إلى "تعديل البروفايل" تحدث مشاكل (غالبًا مشاكل في عرض البيانات أو تحديثها).

    تحليل المشكلة المحتملة

    بما أن وضع الهاتف ووضع الحاسوب يستخدمان نفس الدالة _buildMainContent()، والتابوين (AddProfile و EditProfile) يستخدم نفس الـ FutureBuilder (في EditProfile) وجلب البيانات، فإن السبب غالبًا مرتبط بكيفية التحكّم في حالة التطبيق State وبالأخص التابع TabController.

    الأسباب والمشاكل الشائعة التي قد تسبب هذا السلوك:

    1. مزامنة حالة التبويبات وخيارات إعادة البناء (Rebuilds) في Desktop

    • في الحاسوب، التاب TabBar و TabBarView موجودان داخل عمود وأحيانًا محاطين بـ Expanded أو Container بخصائص مختلفة، مما قد يسبب في إعادة بناء الواجهة بسرعة مختلفة.
    • التغيير في TabController يؤدي إلى استدعاء setState()، أحيانًا تعيد بناء الـ FutureBuilder بشكل غير متوقع.
    • قد يحصل في Desktop أن يتم إعادة بناء تبويبات حتى بدون تغيير في البيانات أو اختيار المستخدم، مما قد يسبب إعادة تحميل بيانات أو تحديثات متكررة غير مرغوبة.

    2. إعادة تحميل البيانات مع كل بناء (Refresh) في Desktop

    • إذا لم يكن هناك caching للبيانات أو إعادة استخدام لقائمة البيانات المحملة، قد يؤدي ذلك إلى انتظار تحميل البيانات في كل مرة يتم فيها إعادة بناء التبويب.
    • في الهاتف، ربما تكون حالة التبويب أو التصفح أكثر استقرارًا أو تبديل التبويبات أقل تواترًا فالأمر لا يظهر كمشكلة.

    3. مشكلة في TabController أو عدم تناسق مع طول التبويبات

    • تحقق أن طول الـ TabController يساوي عدد التبويبات في كل من Desktop والهاتف.
    • أي خطأ في تهيئة الـ _tabController أو تغييره قد يؤدي إلى استثناءات أو إعادة تحميل غير متوقعة.

    4. مشكلة في إعادة تحميل متغيرات تحكم النصوص (TextEditingController)

    • في دالة _loadProfileData() تقوم بتحديث القيم داخل TextEditingController وهذا قد يسبب إعادة بناء مفرطة أو مشاكل في تحديث الواجهة خصوصًا في وضع الحاسوب.

    نصائح وحلول عملية لتشخيص وحل المشكلة

    1. تأكد من أن TabController يتم إنشاؤه مرة واحدة فقط في initState ولا يتم تغييره بقية وقت عمر الويدجت.

    2. راقب وأنت تستخدم الـ FutureBuilder في _buildEditProfileTab() أن الدالة _fetchProfiles() لا تنفّذ بصورة متكررة بدون داعٍ.

      • يمكنك عمل caching للبيانات أو تحميل القائمة مرة واحدة وحفظها في متغير.
      • مثال:
      late Future<List<Map<String, dynamic>>> _profilesFuture;
      
      @override
      void initState() {
        super.initState();
        _tabController = TabController(length: 2, vsync: this);
        _tabController.addListener(_handleTabSelection);
      
        _profilesFuture = _fetchProfiles(); // جلب البيانات مرة واحدة فقط
      }
      
      Widget _buildEditProfileTab() {
        return FutureBuilder<List<Map<String, dynamic>>>(
          future: _profilesFuture, // استخدام القيمة المحفوظة
          builder: (context, snapshot) {
            ...
          }
        );
      }
      
    3. تأكد من عدم تحديث قيم TextEditingController داخل عملية بناء الواجهة مباشرة، بل استعمل _طرق غير مزعجة مثل:

      • تعيين قيم TextEditingController فقط عندما تتغير البيانات (مثلاً داخل _loadProfileData) وليس في كل build.
      • أو استخدم StatefulWidget منفصل لكل تبويب لضمان فصل الحالات.
    4. فحص الأخطاء و logs:

      • تحقق من وجود أي رسائل خطأ في الـ debug console خصوصًا في وضع Desktop.
      • قد يكون هناك خطأ في استدعاء setState أو خطأ في التعامل مع الـ TabController.
    5. التأكد أن _loadProfileData لا يسبب setState مستمرة أو حلقات إعادة بناء


    خلاصة

    • في وضع الهاتف، عادةً الشاشة محدودة والتبويبات أقل تعقيد والتحديث أقل، لذا المشاكل أقل وضوحًا.

    • في وضع الحاسوب، بسبب المزيد من التفاعلات وربما إعادة بناء المتكرر، تحتاج إلى التحكم بشكل أفضل في تحميل البيانات وتحديث الحالة، عن طريق:

      • تحميل البيانات مرة واحدة (caching).
      • التحكم بحالة TextEditingController بحذر.
      • التحقق من عدم تكرار إنشاء TabController أو تعطيله.
      • مراقبة إعادة بناء الواجهة لتجنب إعادة تحميل البيانات دائماً.

    إذا أعطيتني تفاصيل أكثر عن المشكلة (مثلاً رسالة الخطأ أو ماذا "المشاكل" التي تحصل)، أستطيع مساعدتك بشكل أفضل.

    هل ترغب أن أساعدك في تعديل الكود ليحل هذه المشكلة؟

  7. User

    ماذا اقوم بتعديل هنا Widget _buildEditProfileTab() { return FutureBuilder<List<Map<String, dynamic>>>( future: _fetchProfiles(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return Center(child: Text('حدث خطأ في جلب البيانات')); } else if (!snapshot.hasData || snapshot.data!.isEmpty) { return Center(child: Text('لا يوجد بروفايلات متاحة')); }

        final profiles = snapshot.data!;
        return SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(15),
                  border: Border.all(color: Colors.white.withOpacity(0.1)),
                ),
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    Text(
                      'تعديل إعدادات البروفايل',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: _textColor,
                      ),
                    ),
                    SizedBox(height: 16),
    
                    // Dropdown لاختيار البروفايل
                    DropdownButtonFormField<String>(
                      value:
                          profiles.any((p) => p['name'] == _profileName)
                              ? _profileName
                              : null,
                      items:
                          profiles.map((profile) {
                            return DropdownMenuItem<String>(
                              value: profile['name'],
                              child: Text(
                                profile['name'],
                                style: TextStyle(color: _textColor),
                              ),
                            );
                          }).toList(),
                      onChanged: (String? selectedProfile) {
                        if (selectedProfile != null) {
                          _loadProfileData(selectedProfile);
                        }
                      },
                      decoration: InputDecoration(
                        labelText: 'اختر البروفايل للتعديل',
                        labelStyle: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.8),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: _primaryColor),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 14,
                        ),
                        fillColor: _cardColor,
                        filled: true,
                      ),
                      dropdownColor: _cardColor,
                      style: TextStyle(color: _textColor),
                    ),
                    SizedBox(height: 12),
    
                    // حقل حد التحميل
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: downloadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة التحميل',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _downloadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _downloadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
    
                    SizedBox(height: 12),
    
                    // حقل حد الرفع
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: uploadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة الرفع',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _uploadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _uploadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 16),
    
                    ElevatedButton(
                      onPressed: _updateProfile,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        foregroundColor: _textColor,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      child: const Text('تحديث البروفايل'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
    

    }

  8. Assistant

    المشكلة التي تواجهها غالباً سببها أن FutureBuilder في _buildEditProfileTab يقوم باستدعاء _fetchProfiles() في كل مرة يُعاد فيها بناء هذا الودجت، مما يسبب إعادة تحميل البيانات بشكل متكرر في وضع الحاسوب (Desktop) أكثر من الهاتف.

    لحل هذه المشكلة، يجب تحميل البيانات مرة واحدة فقط وحفظها في متغير Future ويتم استخدامه داخل FutureBuilder بحيث لا يعيد تحميل البيانات كل مرة يعاد فيها البناء.


    التعديل المطلوب على الكود:

    1. في متغيرات الحالة (State) أضف متغير من نوع late Future<List<Map<String, dynamic>>> لحفظ النتيجة:
    late Future<List<Map<String, dynamic>>> _profilesFuture;
    
    1. في initState قم بتعيين قيمة Future بتعيين استدعاء جلب البيانات مرة واحدة فقط:
    @override
    void initState() {
      super.initState();
      _tabController = TabController(length: 2, vsync: this);
      _tabController.addListener(_handleTabSelection);
    
      _profilesFuture = _fetchProfiles(); // جلب مرة واحدة فقط
    }
    
    1. عدّل _buildEditProfileTab() لاستخدام المتغير _profilesFuture وليس استدعاء _fetchProfiles() مباشرةً:
    Widget _buildEditProfileTab() {
      return FutureBuilder<List<Map<String, dynamic>>>(
        future: _profilesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return Center(child: CircularProgressIndicator());
          } else if (snapshot.hasError) {
            return Center(child: Text('حدث خطأ في جلب البيانات'));
          } else if (!snapshot.hasData || snapshot.data!.isEmpty) {
            return Center(child: Text('لا يوجد بروفايلات متاحة'));
          }
    
          final profiles = snapshot.data!;
          return SingleChildScrollView(
            padding: EdgeInsets.all(16),
            child: Column(
              // بقية الكود كما هو...
            ),
          );
        }
      );
    }
    

    شرح الفكرة:

    • بنفس الطريقة التي تعمل بها FutureBuilder وعند المرور إلى التبويب الثاني، الـ Future الخاص بجلب البيانات يتم إنشاءه مرة واحدة فقط عند بدء الشاشة ويتم إعادة استخدامه طوال فترة حياة هذه الصفحة.
    • هذا يمنع استدعاء _fetchProfiles() في كل مرة يُعاد فيها بناء الودجت، وهو ما قد يحدث في شاشة الحاسوب نتيجة إعادة بناء الواجهة بسبب حجم الشاشة المختلف، أو حالات أخرى.

    ملاحظة إضافية:

    إذا كنت تريد تحديث البيانات عند حذف أو تعديل البروفايل، يمكنك عمل إعادة تعيين للـ _profilesFuture عن طريق:

    void _refreshProfiles() {
      setState(() {
        _profilesFuture = _fetchProfiles();
      });
    }
    

    وتدعو هذه الدالة في المكان المناسب بعد تحديث البيانات.


    بهذا التعديل ستكون طريقة جلب البيانات موحدة ومستقرة دون مشاكل إعادة تحميل متكررة سواء في الهاتف أو في الحاسوب. إذا أردت المساعدة في أي نقطة أخرى أخبرني!

  9. User

    ظهر هذا The expression doesn't evaluate to a function, so it can't be invoked.dartinvocation_of_non_function_expression

  10. Assistant

    الخطأ "The expression doesn't evaluate to a function, so it can't be invoked" يعني أنك تحاول استدعاء (()) على شيء ليس دالة (function)، أي أنك كتبت استخدام قوسين بعد متغير أو قيمة ليست دالة.


    أين تحدث المشكلة غالبًا في كودك؟

    غالبًا الخطأ ظهر بسبب:

    _profilesFuture = _fetchProfiles(); // هذا صحيح لأنه استدعاء دالة
    

    لكن قد تكون كتبت شيئًا مثل:

    _profilesFuture = _fetchProfiles; // بدون أقواس () !!
    

    و بعد ذلك في FutureBuilder:

    future: _profilesFuture(),
    

    أي أنك تستخدم _profilesFuture() وكأنها دالة، لكنها قيمة من نوع Future، وبالتالي يسبب هذا الخطأ.


    كيف تحل هذه المشكلة؟

    تأكد من التغييرات التالية:

    • قم بتعيين المتغير future بدون أقواس فقط إذا كنت تريد تخزين الدالة نفسها، ولكن هنا أنت تريد استدعاء جلب البيانات لذلك يجب كتابة مع أقواس ()
    _profilesFuture = _fetchProfiles(); // نعطي ناتج الدالة وليس الدالة نفسها
    
    • عند استخدام FutureBuilder:
    future: _profilesFuture,  // هنا ننادي المتغير (الذي يحمل Future) بدون ()
    

    مثال كامل صحيح

    class _HotspotProfileState extends State<HotspotProfile> with SingleTickerProviderStateMixin {
      late Future<List<Map<String, dynamic>>> _profilesFuture;
      
      @override
      void initState() {
        super.initState();
        _tabController = TabController(length: 2, vsync: this);
        _profilesFuture = _fetchProfiles(); // استدعاء الدالة هنا مع ()
      }
      
      Widget _buildEditProfileTab() {
        return FutureBuilder<List<Map<String, dynamic>>>(
          future: _profilesFuture, // بدون أقواس !
          builder: (context, snapshot) {
            // بناء المحتوى...
          },
        );
      }
      
      Future<List<Map<String, dynamic>>> _fetchProfiles() async {
        // جلب البيانات مع await ...
      }
    }
    

    راجع في كودك التالي المواضع:

    • هل قمت بتعيين _profilesFuture بـ _fetchProfiles() (بـ أقواس).
    • هل استخدمت في FutureBuilder future: _profilesFuture فقط، وليس future: _profilesFuture().

    إذا زودتني بالمكان بالضبط الذي تظهر فيه المشكلة في الكود أو السطر الذي تراه يشير إليه الخطأ أستطيع مساعدتك بشكل أدق.

  11. User

    ماذا عن هذة القيمة عند تغييرها حدث مشكلة onChanged: (String? selectedProfile) { if (selectedProfile != null) { _loadProfileData(selectedProfile); } تم قطع الاتصال للعلم الكود import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart' as intl; import 'package:micro_panel/AddHotspotUser.dart'; import 'package:micro_panel/AddUserManagerUser.dart'; import 'package:micro_panel/HelpDesk.dart'; import 'package:micro_panel/HomePage.dart'; import 'package:micro_panel/Login.dart'; import 'package:micro_panel/SendNotes.dart'; import 'package:micro_panel/UserManagerProfile.dart'; import 'package:micro_panel/UserManagerReport.dart'; import 'package:micro_panel/UserManagerUserList.dart'; import 'package:micro_panel/hotspotUserList.dart'; import 'package:path_provider/path_provider.dart'; import 'package:router_os_client/router_os_client.dart'; import 'package:http/http.dart' as http; import 'package:flutter/services.dart';

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

    @override State createState() => _HotspotProfileState(); }

    class _HotspotProfileState extends State with SingleTickerProviderStateMixin { Color _primaryColor = const Color(0xFF3B82F6); Color _backgroundColor = const Color(0xFF0A192F); Color _cardColor = const Color(0xFF172A46); Color _textColor = Colors.white; late TabController _tabController; String _profileName = ''; String _downloadValue = ''; String _uploadValue = '';

    String _profileId = ''; late Future<List<Map<String, dynamic>>> _profilesFuture; String _downloadSpeedUnit = 'كيلو'; String _uploadSpeedUnit = 'كيلو'; final TextEditingController downloadController = TextEditingController(); final TextEditingController uploadController = TextEditingController();

    final TextEditingController _feedbackController = TextEditingController(); final ValueNotifier _ratingNotifier = ValueNotifier(0); final ValueNotifier _feedbackTypeNotifier = ValueNotifier( 'suggestion', ); final ValueNotifier _isSendingNotifier = ValueNotifier(false); int _currentIndex = 0;

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

    @override void dispose() { _feedbackController.dispose(); _ratingNotifier.dispose(); _feedbackTypeNotifier.dispose(); _isSendingNotifier.dispose(); downloadController.dispose(); uploadController.dispose(); _tabController.dispose(); super.dispose(); }

    @override void initState() { super.initState(); _tabController = TabController(length: 2, vsync: this); _tabController.addListener(_handleTabSelection); _profilesFuture = _fetchProfiles(); }

    void _handleTabSelection() { if (_tabController.indexIsChanging) { setState(() {}); } }

    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.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => UsersPage(client: widget.client),
          ),
        );
        break;
      case 2:
        Navigator.pushReplacement(
          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: [ _buildDesktopNavigation(), Expanded( child: Column( children: [ Expanded( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ _backgroundColor.withOpacity(0.9), _backgroundColor.withOpacity(0.7), ], ), ), child: _buildMainContent(), ), ), ], ), ), ], ), ); }

    PreferredSizeWidget _buildAppBar(BuildContext context) { return AppBar( title: const Text( 'إضافة بروفايل', style: TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 17, ), ), backgroundColor: _backgroundColor, centerTitle: true, elevation: 0, leading: Builder( builder: (context) => IconButton( icon: Icon(Icons.menu_rounded, color: _textColor), onPressed: () => Scaffold.of(context).openDrawer(), ), ), ); }

    // تعديل دالة بناء واجهة الهاتف Widget _buildMobileLayout(BuildContext context) { return Scaffold( backgroundColor: _backgroundColor, drawer: _buildUniversalDrawer(), appBar: _buildAppBar(context), body: _buildMainContent(showHeader: false), ); }

    String _convertToRouterUnit(String unit) { if (unit == 'كيلو') return 'K'; if (unit == 'ميجا') return 'M'; return 'K'; // افتراضي }

    Widget _buildMainContent({bool showHeader = true}) { return Column( children: [ Container( height: 60,

          child: TabBar(
            controller: _tabController,
            indicatorColor: _primaryColor,
            indicatorWeight: 3,
            labelColor: _primaryColor,
            unselectedLabelColor: Colors.white.withOpacity(0.5),
            tabs: const [
              Tab(icon: Icon(Icons.speed_rounded), text: 'إضافة بروفايل'),
              Tab(icon: Icon(Icons.edit_note_rounded), text: 'تعديل بروفايل'),
            ],
          ),
        ),
        Expanded(
          child: TabBarView(
            controller: _tabController,
            children: [_buildAddProfileTab(), _buildEditProfileTab()],
          ),
        ),
      ],
    );
    

    }

    Widget _buildAddProfileTab() { return SingleChildScrollView( padding: EdgeInsets.all(16), child: Column( children: [ SizedBox(height: 16), // حاوية خلفية للحقول Container( decoration: BoxDecoration( color: Colors.white.withOpacity(0.05), borderRadius: BorderRadius.circular(15), border: Border.all(color: Colors.white.withOpacity(0.1)), ), padding: EdgeInsets.all(16), child: Column( children: [ Text( 'إعدادات البروفايل', style: TextStyle( fontFamily: 'Tajawal', fontSize: 18, fontWeight: FontWeight.bold, color: _textColor, ), ), SizedBox(height: 16), // حقل إدخال لاسم البروفايل TextField( decoration: InputDecoration( labelText: 'اسم البروفايل', labelStyle: TextStyle( fontFamily: 'Tajawal', color: _textColor.withOpacity(0.8), ), border: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide( color: Colors.white.withOpacity(0.2), ), ), enabledBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide( color: Colors.white.withOpacity(0.2), ), ), focusedBorder: OutlineInputBorder( borderRadius: BorderRadius.circular(8), borderSide: BorderSide(color: _primaryColor), ), contentPadding: EdgeInsets.symmetric( horizontal: 16, vertical: 14, ), fillColor: _cardColor, filled: true, ), style: TextStyle(fontFamily: 'Tajawal', color: textColor), inputFormatters: [ FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9]')), ], onChanged: (value) { setState(() { _profileName = value; }); }, ), SizedBox(height: 12),

                // حقل حد التحميل
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة التحميل',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _downloadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _downloadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _downloadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),
    
                SizedBox(height: 12),
    
                // حقل حد الرفع
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة الرفع',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _uploadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _uploadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _uploadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16),
    
                ElevatedButton(
                  onPressed: () async {
                    if (_profileName.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال اسم البروفايل'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
    
                    if (_downloadValue.isEmpty || _uploadValue.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال قيم السرعة'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }
    
                    try {
                      final response = await widget.client.talk([
                        '/ip/hotspot/user/profile/add',
                        '=name=$_profileName',
                        '=rate-limit=${_downloadValue}${_convertToRouterUnit(_downloadSpeedUnit)}/${_uploadValue}${_convertToRouterUnit(_uploadSpeedUnit)}',
                      ]);
    
                      if (response.isNotEmpty) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('تم إنشاء البروفايل بنجاح'),
                            backgroundColor: Colors.green,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('حدث خطأ أثناء إنشاء البروفايل'),
                            backgroundColor: Colors.red,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      }
                    } catch (e) {
                      print('$e');
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('حدث خطأ اثناء انشاء البروفايل'),
                          backgroundColor: Colors.red,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      );
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _primaryColor,
                    foregroundColor: _textColor,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    minimumSize: const Size(double.infinity, 50),
                  ),
                  child: const Text('إضافة البروفايل'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
    

    }

    Widget _buildEditProfileTab() { return FutureBuilder<List<Map<String, dynamic>>>( future: _profilesFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else if (snapshot.hasError) { return Center(child: Text('حدث خطأ في جلب البيانات')); } else if (!snapshot.hasData || snapshot.data!.isEmpty) { return Center(child: Text('لا يوجد بروفايلات متاحة')); }

        final profiles = snapshot.data!;
        return SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(15),
                  border: Border.all(color: Colors.white.withOpacity(0.1)),
                ),
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    Text(
                      'تعديل إعدادات البروفايل',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: _textColor,
                      ),
                    ),
                    SizedBox(height: 16),
    
                    // Dropdown لاختيار البروفايل
                    DropdownButtonFormField<String>(
                      value:
                          profiles.any((p) => p['name'] == _profileName)
                              ? _profileName
                              : null,
                      items:
                          profiles.map((profile) {
                            return DropdownMenuItem<String>(
                              value: profile['name'],
                              child: Text(
                                profile['name'],
                                style: TextStyle(color: _textColor),
                              ),
                            );
                          }).toList(),
                      onChanged: (String? selectedProfile) {
                        if (selectedProfile != null) {
                          _loadProfileData(selectedProfile);
                        }
                      },
                      decoration: InputDecoration(
                        labelText: 'اختر البروفايل للتعديل',
                        labelStyle: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.8),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: _primaryColor),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 14,
                        ),
                        fillColor: _cardColor,
                        filled: true,
                      ),
                      dropdownColor: _cardColor,
                      style: TextStyle(color: _textColor),
                    ),
                    SizedBox(height: 12),
    
                    // حقل حد التحميل
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: downloadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة التحميل',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _downloadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _downloadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
    
                    SizedBox(height: 12),
    
                    // حقل حد الرفع
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: uploadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة الرفع',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _uploadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _uploadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 16),
    
                    ElevatedButton(
                      onPressed: _updateProfile,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        foregroundColor: _textColor,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      child: const Text('تحديث البروفايل'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
    

    }

    Future _loadProfileData(String profileName) async { try { final response = await widget.client.talk([ '/ip/hotspot/user/profile/print', '?name=$profileName', ]);

      if (response.isNotEmpty) {
        final profile = response.first;
        final rateLimit = profile['rate-limit']?.split('/') ?? ['', ''];
    
        // تحليل قيمة rate-limit
        String downloadValue = '';
        String uploadValue = '';
        String downloadUnit = 'كيلو';
        String uploadUnit = 'كيلو';
    
        if (rateLimit.length == 2) {
          // تحليل سرعة التحميل
          if (rateLimit[0].contains('M')) {
            downloadValue = rateLimit[0].replaceAll('M', '');
            downloadUnit = 'ميجا';
          } else if (rateLimit[0].contains('K')) {
            downloadValue = rateLimit[0].replaceAll('K', '');
            downloadUnit = 'كيلو';
          }
    
          // تحليل سرعة الرفع
          if (rateLimit[1].contains('M')) {
            uploadValue = rateLimit[1].replaceAll('M', '');
            uploadUnit = 'ميجا';
          } else if (rateLimit[1].contains('K')) {
            uploadValue = rateLimit[1].replaceAll('K', '');
            uploadUnit = 'كيلو';
          }
        }
    
        setState(() {
          _profileName = profileName;
          _profileId = profile['.id'] ?? ''; // حفظ معرف البروفايل
          downloadController.text = downloadValue;
          uploadController.text = uploadValue;
          _downloadSpeedUnit = downloadUnit;
          _uploadSpeedUnit = uploadUnit;
        });
      }
    } catch (e) {
      print('Error loading profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحميل بيانات البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
    

    }

    Future _updateProfile() async { if (_profileName.isEmpty) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text('الرجاء اختيار بروفايل للتعديل'), backgroundColor: Colors.red, ), ); return; }

    if (downloadController.text.isEmpty || uploadController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('الرجاء إدخال قيم السرعة'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }
    
    try {
      final command = [
        '/ip/hotspot/user/profile/set',
        '=.id=$_profileId',
        '=rate-limit=${downloadController.text}${_convertToRouterUnit(_downloadSpeedUnit)}/${uploadController.text}${_convertToRouterUnit(_uploadSpeedUnit)}',
      ];
    
      final response = await widget.client.talk(command);
    
      if (response.isEmpty ||
          !response.any((reply) => reply.containsKey('!trap'))) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم تحديث البروفايل بنجاح'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('حدث خطأ أثناء تحديث البروفايل'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      print('Error updating profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحديث البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
    

    }

    Future<List<Map<String, dynamic>>> _fetchProfiles() async { try { final response = await widget.client.talk([ '/ip/hotspot/user/profile/print', '=.proplist=name,rate-limit,.id', ]);

      final uniqueProfiles = <Map<String, dynamic>>[];
      final names = <String>{};
    
      for (var profile in response) {
        if (!names.contains(profile['name'])) {
          names.add(profile['name']!);
          uniqueProfiles.add({
            'name': profile['name'],
            'rate-limit': profile['rate-limit'],
            '.id': profile['.id'],
          });
        }
      }
    
      return uniqueProfiles;
    } catch (e) {
      debugPrint('Error fetching profiles: $e');
      return [];
    }
    

    }

    Widget _buildDesktopNavigation() { return SingleChildScrollView( child: Container( width: 280, height: MediaQuery.of(context).size.height, decoration: BoxDecoration( color: Colors.white.withOpacity(0.05), border: Border( right: BorderSide(color: Colors.white.withOpacity(0.1)), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 30), Padding( padding: const EdgeInsets.symmetric(horizontal: 16), child: Row( children: [ Icon(Icons.speed, color: _primaryColor, size: 28), const SizedBox(width: 10), Text( 'إضافة بروفايل', style: TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold, ), ), ], ), ), const SizedBox(height: 30), Expanded( 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: false, onTap: () { Navigator.pushReplacement( context, MaterialPageRoute( builder: (context) => RouterDetailsPage(client: widget.client), ), ); }, ),

                    // قسم الهوتسبوت (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة الهوتسبوت',
                      icon: Icons.wifi,
                      initiallyExpanded: isHotspotExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHotspotExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        UsersPage(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: true,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.person_add,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.group_add,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),
    
                    // قسم اليوزر مانجر (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة اليوزر مانجر',
                      icon: Icons.manage_accounts,
                      initiallyExpanded: isUserManagerExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isUserManagerExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people_outline,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => UserManagerUserList(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => UserManagerProfile(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.payment_rounded,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.credit_score,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => AddUserManagerCards(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
    
                        _buildNavItem(
                          icon: Icons.assignment,
                          title: 'السجلات',
                          isActive: false,
                          onTap: () {
                            // Navigation code here
                          },
                        ),
                      ],
                    ),
    
                    // قسم الإعدادات والأدوات (قابل للطي)
                    _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: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => HelpDesk(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.feedback,
                          title: 'إرسال ملاحظات',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => SendNotes(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.info_outline,
                          title: 'حول التطبيق',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.logout,
                          title: 'تسجيل الخروج',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (context) => Login()),
                            );
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
    

    }

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

    Widget _buildExpandableSection({ required String title, required IconData icon, required List children, required bool initiallyExpanded, required ValueChanged 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 _buildUniversalDrawer() { return Drawer( backgroundColor: _backgroundColor, child: SafeArea( child: ListView( padding: EdgeInsets.zero, children: [ SizedBox( height: 70, child: DrawerHeader( decoration: BoxDecoration( color: _primaryColor.withOpacity(0.1), border: Border( bottom: BorderSide(color: Colors.white.withOpacity(0.1)), ), ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon( Icons.network_check, size: 30, color: Colors.white, ), const SizedBox(width: 8), Text( 'Micro Panel', style: const TextStyle( fontFamily: 'Tajawal', color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold, ), ), ], ), ], ), ), ),

            // Main Navigation Items
            _buildUniversalDrawerItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) =>
                            RouterDetailsPage(client: widget.client),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
    
            // Hotspot Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة الهوتسبوت',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              initiallyExpanded: true,
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UsersPage(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'البروفايل',
                  onTap: () {},
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.person_add,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.group_add,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),
    
            // User Manager Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(
                    Icons.manage_accounts,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة اليوزر مانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
    
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people_outline,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerUserList(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.speed,
                  title: 'البروفايل',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerProfile(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.payment_rounded,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.credit_score,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerSession(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),
    
            // Settings Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'الإعدادات والأدوات',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.settings,
                  title: 'إعدادات النظام',
                  onTap: () {
                    // 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: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                HelpDesk(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                SendNotes(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),
    
            const Divider(color: Colors.white24),
    
            // Logout Item
            _buildUniversalDrawerItem(
              icon: Icons.logout,
              title: 'تسجيل خروج',
              color: Colors.red,
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) => Login(),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
    

    }

    Widget _buildUniversalDrawerItem({ required IconData icon, required String title, Color color = Colors.white, required VoidCallback onTap, }) { return ListTile( leading: Icon(icon, color: color), title: Text( title, style: TextStyle(fontFamily: 'Tajawal', color: color, fontSize: 14), ), onTap: onTap, contentPadding: const EdgeInsets.symmetric(horizontal: 16), ); }

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

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

    للعلم المشكلة تحدث عن التشغيل في شاشة الهاتف

  12. Assistant

    المشكلة التي تحدث عند اختيار عنصر من Dropdown في شاشة الهاتف (وهي تعمل في شاشة الحاسوب) قد تكون ناجمة عن تعارض في حالة الـ state أو تحديث غير متزامن للـ TextEditingController والقيم المتعلقة به (مثل _profileName, _downloadSpeedUnit, وغيرها) أثناء تحميل بيانات البروفايل.


    الأسباب المحتملة وكيفية إصلاحها:

    1. تحديث القيم داخل _loadProfileData مع setState

    عند استدعاء _loadProfileData يتم جلب بيانات البروفايل وتحديث الـ TextEditingController والقيم باستخدام setState. في بعض الأحيان، خاصة في بيئة الهاتف (مع معاودة بناء واجهات UI بشكل متكرر) قد يؤدي ذلك إلى تعارض أو إعادة بناء مفرطة تسبب مشاكل.


    2. مشكلة في تحديث DropdownButtonFormField أو TextField بعد تحميل البيانات

    عند تغيير قيم TextEditingController مباشرة (كـ downloadController.text = downloadValue;) داخل setState قد تؤدي إلى خطأ أو سلوك غير متوقع، خصوصًا إذا حدث أثناء بناء الواجهة.


    كيف تحسن الكود:

    أ. قم بجعل تحميل البيانات في _loadProfileData خارج setState لتجنب إعادة بناء قبل الانتهاء من تحديث القيم، ثم داخل setState فقط حدث المتغيرات (وليس TextEditingController.text مباشرة):

    Future<void> _loadProfileData(String profileName) async {
      try {
        final response = await widget.client.talk([
          '/ip/hotspot/user/profile/print',
          '?name=$profileName',
        ]);
    
        if (response.isNotEmpty) {
          final profile = response.first;
          final rateLimit = profile['rate-limit']?.split('/') ?? ['', ''];
    
          String downloadValue = '';
          String uploadValue = '';
          String downloadUnit = 'كيلو';
          String uploadUnit = 'كيلو';
    
          if (rateLimit.length == 2) {
            if (rateLimit[0].contains('M')) {
              downloadValue = rateLimit[0].replaceAll('M', '');
              downloadUnit = 'ميجا';
            } else if (rateLimit[0].contains('K')) {
              downloadValue = rateLimit[0].replaceAll('K', '');
              downloadUnit = 'كيلو';
            }
    
            if (rateLimit[1].contains('M')) {
              uploadValue = rateLimit[1].replaceAll('M', '');
              uploadUnit = 'ميجا';
            } else if (rateLimit[1].contains('K')) {
              uploadValue = rateLimit[1].replaceAll('K', '');
              uploadUnit = 'كيلو';
            }
          }
    
          // تحديث الحالة بالإضافة لفصل تحديث الـ TextEditingController
          setState(() {
            _profileName = profileName;
            _profileId = profile['.id'] ?? '';
            _downloadSpeedUnit = downloadUnit;
            _uploadSpeedUnit = uploadUnit;
          });
    
          // غير داخل setState لتجنب مشاكل إعادة بناء غير مرغوب
          downloadController.text = downloadValue;
          uploadController.text = uploadValue;
        }
      } catch (e) {
        print('Error loading profile: $e');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('حدث خطأ أثناء تحميل بيانات البروفايل'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
    

    ب. تأكد من أن عند استدعاء _loadProfileData في onChanged الخاص بـ Dropdown لا تسبب استدعاء setState() متكرراً أو دائرياً.

    يمكنك إضافة طباعة للتأكد أو التأكد أن القيمة مختلفة فعليًا قبل تحديث الحالة:

    onChanged: (String? selectedProfile) {
      if (selectedProfile != null && selectedProfile != _profileName) {
        _loadProfileData(selectedProfile);
      }
    },
    

    ج. يمكنك أيضًا تجربة وضوح تزامن عمليات تحميل البيانات عند تغير الـ Dropdown بإضافة انتظار بسيط أو قفل (loading indicator) أثناء تحميل البيانات لتجنب عمليات متزامنة.


    ملخص:

    • فصل تحديث قيم الـ TextEditingController عن setState.
    • تحديث المتغيرات التي تؤثر على UI فقط داخل setState.
    • التأكد من تحديث الحالة فقط عند تغيّر القيم فعلاً لتجنّب التحديثات المتكررة.
    • إدارة تحميل البيانات بشكل متسلسل ومرن لتجنب حالات التداخل خاصة في شاشة الهاتف.

    إذا استمرت المشكلة معك، يمكنك أيضًا تجربة:

    • استخدام ValueNotifier أو ChangeNotifier لإدارة حالة الحقول النصية والبيانات.
    • تجزئة الصفحة إلى Widgets أصغر مع StatefulWidget منفصل لكل تبويب لتقليل تعقيد الحالة.

    أخبرني إن أردت مساعدتك بتعديل تفصيلي على أي جزء من الكود.