اريد ان اجعل اسلوب التعديل في هذا الكود
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<HotspotProfile> createState() => _HotspotProfileState();
}

class _HotspotProfileState extends State<HotspotProfile>
    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<int> _ratingNotifier = ValueNotifier(0);
  final ValueNotifier<String> _feedbackTypeNotifier = ValueNotifier(
    'suggestion',
  );
  final ValueNotifier<bool> _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: _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);
                          setState(() {});
                        }
                      },
                      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<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('/') ?? ['', ''];

        // تحليل قيمة 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<void> _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<Widget> children,
    required bool initiallyExpanded,
    required ValueChanged<bool> onExpansionChanged,
  }) {
    return ExpansionTile(
      title: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            Icon(icon, color: Colors.white.withOpacity(0.7), size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
      childrenPadding: const EdgeInsets.only(left: 16),
      collapsedIconColor: Colors.white.withOpacity(0.7),
      iconColor: Colors.white.withOpacity(0.7),
      initiallyExpanded: initiallyExpanded,
      onExpansionChanged: onExpansionChanged,
      children: children,
    );
  }

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

مشابة لهذا اي اجعلة يجلب اسم البروفايل فقط والتعديل على حسب الحقول التي سيتم ادخالها
الكود الاخر
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/HotspotProfile.dart';
import 'package:micro_panel/Login.dart';
import 'package:micro_panel/SendNotes.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 UserManagerProfile extends StatefulWidget {
  final RouterOSClient client;
  const UserManagerProfile({super.key, required this.client});

  @override
  State<UserManagerProfile> createState() => _UserManagerProfileState();
}

class _UserManagerProfileState extends State<UserManagerProfile>
    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 _validityValue = '';
  String _validityUnit = 'أيام';
  String _downloadLimitValue = '';
  String _downloadLimitUnit = 'ميجابايت';
  String _uptimeLimitValue = '';
  String _uptimeLimitUnit = 'ساعات';

  String _profileNameForUsers = '';
  String _price = '';
  String _validity = '';
  String _downloadLimit = '';
  String _uploadLimit = '';
  String _uptimeLimit = '';

  String _profileId = '';
  String _limitationId = '';
  String _limitation_number = '';

  final TextEditingController _downloadLimitController =
      TextEditingController();
  final TextEditingController _uploadLimitController = TextEditingController();
  final TextEditingController _uptimeLimitController = TextEditingController();
  final TextEditingController _nameForUsersController = TextEditingController();
  final TextEditingController _priceController = TextEditingController();
  final TextEditingController _validityController = TextEditingController();
  final TextEditingController _transferLimitController =
      TextEditingController();

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

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

  @override
  void dispose() {
    _downloadLimitController.dispose();
    _uploadLimitController.dispose();
    _uptimeLimitController.dispose();
    _nameForUsersController.dispose();
    _priceController.dispose();
    _validityController.dispose();
    _transferLimitController.dispose();
    _feedbackController.dispose();
    _ratingNotifier.dispose();
    _feedbackTypeNotifier.dispose();
    _isSendingNotifier.dispose();
    _tabController.dispose();
    super.dispose();
  }

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

    Future.delayed(Duration(microseconds: 150), () {
      _getRouterVersion();
    });
  }

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

  String getValidity() {
    if (_validityValue.isEmpty) return '1d';
    switch (_validityUnit) {
      case 'أيام':
        return '${_validityValue}d';
      case 'ساعات':
        return '${_validityValue}h';
      case 'دقائق':
        return '${_validityValue}m';
      default:
        return '${_validityValue}d';
    }
  }

  String getDownloadLimit() {
    if (_downloadLimitValue.isEmpty) return '0';
    switch (_downloadLimitUnit) {
      case 'بايت':
        return _downloadLimitValue;
      case 'كيلوبايت':
        return '${int.parse(_downloadLimitValue) * 1024}';
      case 'ميجابايت':
        return '${int.parse(_downloadLimitValue) * 1024 * 1024}';
      case 'جيجابايت':
        return '${int.parse(_downloadLimitValue) * 1024 * 1024 * 1024}';
      default:
        return _downloadLimitValue;
    }
  }

  String getUptimeLimit() {
    if (_uptimeLimitValue.isEmpty) return '0s';
    switch (_uptimeLimitUnit) {
      case 'ثواني':
        return '${_uptimeLimitValue}s';
      case 'دقائق':
        return '${_uptimeLimitValue}m';
      case 'ساعات':
        return '${_uptimeLimitValue}h';
      case 'أيام':
        return '${_uptimeLimitValue}d';
      default:
        return '${_uptimeLimitValue}s';
    }
  }

  Future<int> _getRouterVersion() async {
    try {
      final maindirectory = await getApplicationDocumentsDirectory();
      final saveDirectory = Directory('${maindirectory.path}/MicropanelSecrt');
      if (!await saveDirectory.exists()) {
        await saveDirectory.create(recursive: true);
      }
      final file = File('${saveDirectory.path}/router_version.json');

      if (await file.exists()) {
        final content = await file.readAsString();

        print('محتوى الملف كـ String: $content');

        final jsonData = jsonDecode(content);
        print('البيانات المحلولة من JSON: $jsonData');
        print('الإصدار الموجود في الملف: ${jsonData['router_version']}');

        return int.tryParse(jsonData['router_version'].toString()) ?? 6;
      }

      print('الملف غير موجود، سيتم استخدام الإصدار الافتراضي.');
      return 6;
    } catch (e) {
      print('حدث خطأ أثناء قراءة ملف الإصدار:  ');
      return 6;
    }
  }

  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),
                    ),
                    hintStyle: TextStyle(
                      // إضافة style للنص التوضيحي
                      color: _textColor.withOpacity(0.6),
                      fontFamily: 'Tajawal',
                    ),
                    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: Colors.white, // تحديد اللون الأبيض صراحة
                    fontSize: 16, // حجم الخط
                  ),
                  cursorColor: Colors.white, // لون المؤشر
                  inputFormatters: [
                    FilteringTextInputFormatter.allow(RegExp(r'[a-zA-Z0-9_]')),
                  ],
                  onChanged: (value) {
                    _profileName = value;
                  },
                ),
                SizedBox(height: 12),

                // حقل اسم البروفايل للمستخدمين
                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),
                  onChanged: (value) {
                    _profileNameForUsers = value;
                  },
                ),
                SizedBox(height: 12),

                // حقل السعر
                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: Colors.white),
                  keyboardType: TextInputType.number,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  onChanged: (value) {
                    _price = 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.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color:
                              Colors
                                  .white, // هنا تحديد اللون الأبيض للكتابة داخل الحقل
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          _validityValue = value;
                        },
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: _cardColor,
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(8),
                            bottomLeft: Radius.circular(8),
                          ),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        child: DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            value: _validityUnit,
                            items:
                                ['أيام', 'ساعات', 'دقائق'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 8,
                                      ),
                                      child: Text(
                                        unit,
                                        style: TextStyle(
                                          fontFamily: 'Tajawal',
                                          color: _textColor,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              _validityUnit = newValue!;
                            },
                            dropdownColor: _cardColor,
                            icon: Icon(
                              Icons.arrow_drop_down,
                              color: _textColor,
                            ),
                            isExpanded: true,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12),

                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'حد البيانات',
                          hintText: 'أدخل القيمة الرقمية',
                          hintStyle: TextStyle(
                            color: _textColor.withOpacity(0.8),
                          ),
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color:
                              Colors
                                  .white, // هنا تحديد اللون الأبيض للكتابة داخل الحقل
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          _downloadLimitValue = value;
                        },
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: _cardColor,
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(8),
                            bottomLeft: Radius.circular(8),
                          ),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        constraints: BoxConstraints(minWidth: 100),
                        child: DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            value: _downloadLimitUnit,
                            items:
                                [
                                  'بايت',
                                  'كيلوبايت',
                                  'ميجابايت',
                                  'جيجابايت',
                                ].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 8,
                                      ),
                                      child: Text(
                                        unit,
                                        style: TextStyle(
                                          fontFamily: 'Tajawal',
                                          color: _textColor,
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              _downloadLimitUnit = newValue!;
                            },
                            dropdownColor: _cardColor,
                            icon: Icon(
                              Icons.arrow_drop_down,
                              color: _textColor,
                            ),
                            isExpanded:
                                true, // توسيع العنصر لملء المساحة المتاحة
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 12),

                // حقل حد الوقت مع Dropdown للوحدات
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'حد الوقت',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.only(
                              topRight: Radius.circular(8),
                              bottomRight: Radius.circular(8),
                            ),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color:
                              Colors
                                  .white, // هنا تحديد اللون الأبيض للكتابة داخل الحقل
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          _uptimeLimitValue = value;
                        },
                      ),
                    ),
                    Expanded(
                      child: Container(
                        decoration: BoxDecoration(
                          color: _cardColor,
                          borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(8),
                            bottomLeft: Radius.circular(8),
                          ),
                          border: Border.all(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        constraints: BoxConstraints(
                          minWidth: 100,
                        ), // حد أدنى للعرض
                        child: DropdownButtonHideUnderline(
                          child: DropdownButton<String>(
                            value: _uptimeLimitUnit,
                            items:
                                ['ثواني', 'دقائق', 'ساعات', 'أيام'].map((
                                  String unit,
                                ) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 12,
                                      ), // زيادة المسافة الأفقية
                                      child: Text(
                                        unit,
                                        style: TextStyle(
                                          fontFamily: 'Tajawal',
                                          color: _textColor,
                                          fontSize: 14, // حجم خط مناسب
                                        ),
                                        overflow: TextOverflow.ellipsis,
                                        textAlign:
                                            TextAlign
                                                .right, // محاذاة للنصوص العربية
                                      ),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              _uptimeLimitUnit = newValue!;
                            },
                            dropdownColor: _cardColor,
                            icon: Icon(
                              Icons.arrow_drop_down,
                              color: _textColor,
                            ),
                            isExpanded: true,
                            style: TextStyle(
                              // نمط النص الرئيسي
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16),

                ElevatedButton(
                  onPressed: () async {
                    // التحقق من الحقول المطلوبة
                    if (_profileName.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال اسم البروفايل'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }

                    // تحويل القيم إلى الصيغة الصحيحة
                    final validity = getValidity();
                    final downloadLimit = getDownloadLimit();
                    final uptimeLimit = getUptimeLimit();

                    // التحقق من القيم
                    if (validity == '0d' ||
                        validity == '0h' ||
                        validity == '0m') {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال مدة صلاحية صحيحة'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }

                    try {
                      final routerVersion = await _getRouterVersion();
                      final isVersion7 = routerVersion >= 7;

                      final profileResponse = await widget.client.talk([
                        isVersion7
                            ? '/user-manager/profile/add'
                            : '/tool/user-manager/profile/add',
                        '=name=$_profileName',
                        '=name-for-users=${_profileNameForUsers.isNotEmpty ? _profileNameForUsers : _profileName}',
                        '=price=${_price.isNotEmpty ? _price : "0"}',
                        isVersion7
                            ? '=starts-when=first-auth'
                            : '=starts-at=logon',
                        '=validity=$validity',
                        if (!isVersion7) '=owner=admin',
                      ]);

                      if (profileResponse.isNotEmpty) {
                        // إنشاء القيود
                        final limitationResponse = await widget.client.talk([
                          isVersion7
                              ? '/user-manager/limitation/add'
                              : '/tool/user-manager/profile/limitation/add',
                          '=name=$_profileName',
                          if (!isVersion7) '=owner=admin',
                          '=transfer-limit=${downloadLimit != "0" ? "${downloadLimit}B" : "0B"}',
                          '=uptime-limit=$uptimeLimit',
                        ]);
                        if (profileResponse.isNotEmpty) {
                          // إنشاء القيود
                          final limitationResponse = await widget.client.talk([
                            isVersion7
                                ? '/user-manager/profile-limitation/add'
                                : '/tool/user-manager/profile/profile-limitation/add',
                            '=from-time=0s',
                            '=limitation=$_profileName',
                            '=profile=$_profileName',
                            '=till-time=23h59m59s',
                          ]);
                        }

                        if (limitationResponse.isNotEmpty) {
                          // إعادة تعيين الحقول بعد الإضافة الناجحة
                          setState(() {
                            _profileName = '';
                            _profileNameForUsers = '';
                            _price = '';
                            _validityValue = '';
                            _downloadLimitValue = '';
                            _uptimeLimitValue = '';
                          });

                          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,
                          ),
                        );
                      }
                    } catch (e) {
                      print('Error creating profile: $e');
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text(
                            'حدث خطأ أثناء إنشاء البروفايل: ${e.toString()}',
                          ),
                          backgroundColor: Colors.red,
                        ),
                      );
                    }
                  },
                  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 StatefulBuilder(
      builder: (context, setInnerState) {
        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(
              child: Padding(
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    SizedBox(height: 16),
                    Container(
                      padding: EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.05),
                        borderRadius: BorderRadius.circular(15),
                        border: Border.all(
                          color: Colors.white.withOpacity(0.1),
                        ),
                      ),
                      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),

                          // حقل اسم البروفايل للمستخدمين
                          TextField(
                            controller: _nameForUsersController,
                            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,
                            ),
                          ),
                          SizedBox(height: 12),

                          // حقل السعر (معدل لقبول الأرقام فقط)
                          TextField(
                            controller: _priceController,
                            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:
                                  Colors
                                      .white, // هنا تحديد اللون الأبيض للكتابة داخل الحقل
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                          SizedBox(height: 12),

                          // حقل مدة الصلاحية مع Dropdown للوحدات (معدل لقبول الأرقام فقط)
                          Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: TextField(
                                  controller: _validityController,
                                  decoration: InputDecoration(
                                    labelText: 'مدة الصلاحية',
                                    labelStyle: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: _textColor.withOpacity(0.8),
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    focusedBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: _primaryColor,
                                      ),
                                    ),
                                    contentPadding: EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 14,
                                    ),
                                    fillColor: _cardColor,
                                    filled: true,
                                  ),
                                  style: TextStyle(
                                    fontFamily: 'Tajawal',
                                    color: Colors.white,
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                  onChanged: (value) {},
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: _cardColor,
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(8),
                                      bottomLeft: Radius.circular(8),
                                    ),
                                    border: Border.all(
                                      color: Colors.white.withOpacity(0.2),
                                    ),
                                  ),
                                  child: DropdownButtonHideUnderline(
                                    child: DropdownButton<String>(
                                      value: _validityUnit,
                                      items:
                                          ['أيام', 'ساعات', 'دقائق'].map((
                                            String unit,
                                          ) {
                                            return DropdownMenuItem<String>(
                                              value: unit,
                                              child: Padding(
                                                padding: EdgeInsets.symmetric(
                                                  horizontal: 8,
                                                ),
                                                child: Text(
                                                  unit,
                                                  style: TextStyle(
                                                    fontFamily: 'Tajawal',
                                                    color: _textColor,
                                                  ),
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            );
                                          }).toList(),
                                      onChanged: (String? newValue) {
                                        _validityUnit = newValue!;
                                      },
                                      dropdownColor: _cardColor,
                                      icon: Icon(
                                        Icons.arrow_drop_down,
                                        color: _textColor,
                                      ),
                                      isExpanded: true,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 12),

                          // حد البيانات مع Dropdown
                          Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: TextField(
                                  controller: _transferLimitController,
                                  decoration: InputDecoration(
                                    labelText: 'حد البيانات',
                                    hintText: 'أدخل القيمة الرقمية',
                                    hintStyle: TextStyle(
                                      color: _textColor.withOpacity(0.8),
                                    ),
                                    labelStyle: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: _textColor.withOpacity(0.8),
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    focusedBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: _primaryColor,
                                      ),
                                    ),
                                    contentPadding: EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 14,
                                    ),
                                    fillColor: _cardColor,
                                    filled: true,
                                  ),
                                  style: TextStyle(
                                    fontFamily: 'Tajawal',
                                    color: Colors.white,
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                  onChanged: (value) {},
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: _cardColor,
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(8),
                                      bottomLeft: Radius.circular(8),
                                    ),
                                    border: Border.all(
                                      color: Colors.white.withOpacity(0.2),
                                    ),
                                  ),
                                  constraints: BoxConstraints(minWidth: 100),
                                  child: DropdownButtonHideUnderline(
                                    child: DropdownButton<String>(
                                      value: _downloadLimitUnit,
                                      items:
                                          [
                                            'بايت',
                                            'كيلوبايت',
                                            'ميجابايت',
                                            'جيجابايت',
                                          ].map((String unit) {
                                            return DropdownMenuItem<String>(
                                              value: unit,
                                              child: Padding(
                                                padding: EdgeInsets.symmetric(
                                                  horizontal: 8,
                                                ),
                                                child: Text(
                                                  unit,
                                                  style: TextStyle(
                                                    fontFamily: 'Tajawal',
                                                    color: _textColor,
                                                  ),
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                ),
                                              ),
                                            );
                                          }).toList(),
                                      onChanged: (String? newValue) {
                                        _downloadLimitUnit = newValue!;
                                      },
                                      dropdownColor: _cardColor,
                                      icon: Icon(
                                        Icons.arrow_drop_down,
                                        color: _textColor,
                                      ),
                                      isExpanded: true,
                                    ),
                                  ),
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 12),

                          // حد الوقت مع Dropdown
                          Row(
                            children: [
                              Expanded(
                                flex: 3,
                                child: TextField(
                                  controller: _uptimeLimitController,
                                  decoration: InputDecoration(
                                    labelText: 'حد الوقت',
                                    labelStyle: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: _textColor.withOpacity(0.8),
                                    ),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    enabledBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: Colors.white.withOpacity(0.2),
                                      ),
                                    ),
                                    focusedBorder: OutlineInputBorder(
                                      borderRadius: BorderRadius.only(
                                        topRight: Radius.circular(8),
                                        bottomRight: Radius.circular(8),
                                      ),
                                      borderSide: BorderSide(
                                        color: _primaryColor,
                                      ),
                                    ),
                                    contentPadding: EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 14,
                                    ),
                                    fillColor: _cardColor,
                                    filled: true,
                                  ),
                                  style: TextStyle(
                                    fontFamily: 'Tajawal',
                                    color: Colors.white,
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                  onChanged: (value) {},
                                ),
                              ),
                              Expanded(
                                child: Container(
                                  decoration: BoxDecoration(
                                    color: _cardColor,
                                    borderRadius: BorderRadius.only(
                                      topLeft: Radius.circular(8),
                                      bottomLeft: Radius.circular(8),
                                    ),
                                    border: Border.all(
                                      color: Colors.white.withOpacity(0.2),
                                    ),
                                  ),
                                  constraints: BoxConstraints(minWidth: 100),
                                  child: DropdownButtonHideUnderline(
                                    child: DropdownButton<String>(
                                      value: _uptimeLimitUnit,
                                      items:
                                          [
                                            'ثواني',
                                            'دقائق',
                                            'ساعات',
                                            'أيام',
                                          ].map((String unit) {
                                            return DropdownMenuItem<String>(
                                              value: unit,
                                              child: Padding(
                                                padding: EdgeInsets.symmetric(
                                                  horizontal: 12,
                                                ),
                                                child: Text(
                                                  unit,
                                                  style: TextStyle(
                                                    fontFamily: 'Tajawal',
                                                    color: _textColor,
                                                    fontSize: 14,
                                                  ),
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  textAlign: TextAlign.right,
                                                ),
                                              ),
                                            );
                                          }).toList(),
                                      onChanged: (String? newValue) {
                                        _uptimeLimitUnit = newValue!;
                                      },
                                      dropdownColor: _cardColor,
                                      icon: Icon(
                                        Icons.arrow_drop_down,
                                        color: _textColor,
                                      ),
                                      isExpanded: true,
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        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<void> _loadProfileData(String profileName) async {
    try {
      final routerVersion = await _getRouterVersion();
      final isVersion7 = routerVersion >= 7;
      // جلب بيانات البروفايل
      final profileResponse = await widget.client.talk([
        isVersion7
            ? '/user-manager/profile/print'
            : '/tool/user-manager/profile/print',
        '?name=$profileName',
      ]);

      if (profileResponse.isNotEmpty) {
        final profile = profileResponse.first;

        // جلب بيانات القيود (بإمكانك حتى حذفها إذا لم تعد تحتاجها)
        final limitationResponse = await widget.client.talk([
          isVersion7
              ? '/user-manager/profile/print'
              : '/tool/user-manager/profile/print',
          '?name=$profileName',
        ]);
        final limitation =
            limitationResponse.isNotEmpty ? limitationResponse.first : {};

        // تحديث الحقول بدون مدة الصلاحية، حد البيانات، وحد الوقت
        setState(() {
          _profileName = profileName;
          _profileId = profile['.id'] ?? '';
          _limitationId = limitation['.id'] ?? '';
          _limitation_number = limitation['numbers'] ?? '';

          _nameForUsersController.text =
              profile['name-for-users'] ?? profileName;
          _priceController.text = profile['price'] ?? '0';
        });
      }
    } catch (e) {
      print('Error loading profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'حدث خطأ أثناء تحميل بيانات البروفايل: ${e.toString()}',
          ),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

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

    String convertValidity(String value, String unit) {
      if (value.isEmpty) return '1d';

      int val = int.tryParse(value) ?? 1;

      switch (unit) {
        case 'أيام':
          return '${val}d 00:00:00';
        case 'ساعات':
          String hours = val.toString().padLeft(2, '0');
          return '$hours:00:00';
        case 'دقائق':
          String minutes = val.toString().padLeft(2, '0');
          return '00:$minutes:00';
        default:
          return '${val}d 00:00:00';
      }
    }

    String convertDownloadLimit(String value, String unit) {
      if (value.isEmpty) return '0';

      int val = int.tryParse(value) ?? 0;

      switch (unit) {
        case 'بايت':
          return val.toString();
        case 'كيلوبايت':
          return (val * 1024).toString();
        case 'ميجابايت':
          return (val * 1024 * 1024).toString();
        case 'جيجابايت':
          return (val * 1024 * 1024 * 1024).toString();
        default:
          return val.toString();
      }
    }

    String convertUptimeLimit(String value, String unit) {
      if (value.isEmpty) return '0s';

      int val = int.tryParse(value) ?? 0;

      switch (unit) {
        case 'ثواني':
          return '${val}s';
        case 'دقائق':
          return '${val}m';
        case 'ساعات':
          String hours = val.toString().padLeft(2, '0');
          return '$hours:00:00';
        case 'أيام':
          return '${val}d';
        default:
          return '${val}s';
      }
    }

    try {
      final routerVersion = await _getRouterVersion();
      final isVersion7 = routerVersion >= 7;

      final validityValue =
          _validityController.text.isNotEmpty ? _validityController.text : '1';
      final validity = convertValidity(validityValue, _validityUnit);

      final downloadLimitValue =
          _transferLimitController.text.isNotEmpty
              ? _transferLimitController.text
              : '0';
      final downloadLimit = convertDownloadLimit(
        downloadLimitValue,
        _downloadLimitUnit,
      );

      final uptimeLimitValue =
          _uptimeLimitController.text.isNotEmpty
              ? _uptimeLimitController.text
              : '0';
      final uptimeLimit = convertUptimeLimit(
        uptimeLimitValue,
        _uptimeLimitUnit,
      );

      final profileCommand = [
        isVersion7
            ? '/user-manager/profile/set'
            : '/tool/user-manager/profile/set',
        '=.id=$_profileId',
        '=name-for-users=${_nameForUsersController.text.isNotEmpty ? _nameForUsersController.text : _profileName}',
        '=price=${_priceController.text.isNotEmpty ? _priceController.text : "0"}',
        '=validity=$validity',
      ];

      final profileResponse = await widget.client.talk(profileCommand);
      print('$profileResponse');
      final limitationCommand = [
        isVersion7
            ? '/user-manager/limitation/set'
            : '/tool/user-manager/profile/limitation/set',
        '=numbers=$_limitation_number',
        '=transfer-limit=${downloadLimit != "0" ? "${downloadLimit}B" : "0B"}',
        '=uptime-limit=$uptimeLimit',
      ];
      final limitationResponse = await widget.client.talk(limitationCommand);

      print('$limitationResponse');

      if (limitationResponse.isNotEmpty ||
          !profileResponse.any((reply) => reply.containsKey('!trap'))) {
        // تفريغ الحقول بعد التحديث الناجح
        setState(() {
          _validityController.clear();
          _transferLimitController.clear();
          _uptimeLimitController.clear();

          // إزالة القيم المخزنة لو تستخدمها أيضاً
          _validityUnit = 'أيام';
          _downloadLimitUnit =
              'ميجابايت'; // إن أردت إعادة وحدة حد البيانات للوضع الافتراضي
          _uptimeLimitUnit = 'ساعات'; // إعادة وحدة حد الوقت للوضع الافتراضي
        });

        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 routerVersion = await _getRouterVersion();
      final isVersion7 = routerVersion >= 7;
      final response = await widget.client.talk([
        isVersion7
            ? '/user-manager/profile/print'
            : '/tool/user-manager/profile/print',
      ]);

      return response
          .map(
            (profile) => {
              'name': profile['name'],
              'name-for-users': profile['name-for-users'],
              'price': profile['price'],
            },
          )
          .toList();
    } catch (e) {
      print('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: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        HotspotProfile(client: widget.client),
                              ),
                            );
                          },
                        ),

                        _buildNavItem(
                          icon: Icons.person_add,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.group_add,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),

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

                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: true,
                          onTap: () {},
                        ),
                        _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<Widget> children,
    required bool initiallyExpanded,
    required ValueChanged<bool> onExpansionChanged,
  }) {
    return ExpansionTile(
      title: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            Icon(icon, color: Colors.white.withOpacity(0.7), size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
      childrenPadding: const EdgeInsets.only(left: 16),
      collapsedIconColor: Colors.white.withOpacity(0.7),
      iconColor: Colors.white.withOpacity(0.7),
      initiallyExpanded: initiallyExpanded,
      onExpansionChanged: onExpansionChanged,
      children: children,
    );
  }

  Widget _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,
                    ),
                  ),
                ],
              ),
              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.speed,
                  title: 'البروفايل',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                HotspotProfile(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.person_add,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.group_add,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),

            // User Manager Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(
                    Icons.manage_accounts,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة اليوزر مانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              initiallyExpanded: true,
              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: () {},
                ),
                _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),
          ),
        ),
      ),
    );
  }
}

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