لماذا حقل الصلاحية بالايام يحتوي على مشكلة لا يعمل في حال تعديل البروفايل يقوم بادخال القيمة بتنسيق خاطأ اريد ان يكون التنسيق مشابة لحقل اضافة البروفايل
الكود
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/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 = '';

  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 = true;
  bool isUserManagerExpanded = false;
  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);
  }

  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,
          color: Colors.white.withOpacity(0.05),
          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';
    }
  }

  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) {
                    _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,
                  ),
                  keyboardType: TextInputType.number,
                  inputFormatters: [FilteringTextInputFormatter.digitsOnly],
                  onChanged: (value) {
                    _price = value;
                  },
                ),
                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,
                        ),
                        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),

                // حقل حد البيانات مع Dropdown للوحدات
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'حد البيانات',
                          hintText: 'أدخل القيمة الرقمية',
                          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,
                        ),
                        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,
                        ),
                        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 profileResponse = await widget.client.talk([
                        '/user-manager/profile/add',
                        '=name=$_profileName',
                        '=name-for-users=${_profileNameForUsers.isNotEmpty ? _profileNameForUsers : _profileName}',
                        '=price=${_price.isNotEmpty ? _price : "0"}',
                        '=starts-when=first-auth',
                        '=validity=$validity',
                      ]);

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

                        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,
                            ),
                            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,
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                ),
                              ),
                              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: 'أدخل القيمة الرقمية',
                                    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,
                                  ),
                                  keyboardType: TextInputType.number,
                                  inputFormatters: [
                                    FilteringTextInputFormatter.digitsOnly,
                                  ],
                                  onChanged: (value) {
                                    setInnerState(() {
                                      _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(
                                  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,
                                  ),
                                  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: _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 profileResponse = await widget.client.talk([
        '/user-manager/profile/print',
        '?name=$profileName',
      ]);

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

        // جلب بيانات القيود
        final limitationResponse = await widget.client.talk([
          '/user-manager/limitation/print',
          '?name=$profileName',
        ]);

        final limitation =
            limitationResponse.isNotEmpty ? limitationResponse.first : {};

        setState(() {
          _profileName = profileName;
          _profileId = profile['.id'] ?? '';
          _limitationId = limitation['.id'] ?? '';

          _nameForUsersController.text = profile['name-for-users'] ?? '';
          _priceController.text = profile['price'] ?? '0';
          _validityController.text = profile['validity'] ?? '1d';

          String transferLimit = limitation['transfer-limit'] ?? '0B';
          if (transferLimit.endsWith('B')) {
            transferLimit = transferLimit.substring(
              0,
              transferLimit.length - 1,
            );
          }
          _downloadLimitController.text = transferLimit;

          _uptimeLimitController.text = limitation['uptime-limit'] ?? '0s';
        });
      }
    } 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;
    }

    try {
      // تحديث البروفايل
      final profileCommand = [
        '/user-manager/profile/set',
        '=.id=$_profileId',
        '=name-for-users=${_nameForUsersController.text.isNotEmpty ? _nameForUsersController.text : _profileName}',
        '=price=${_priceController.text.isNotEmpty ? _priceController.text : "0"}',
        '=validity=${_validityController.text.isNotEmpty ? _validityController.text : "1d"}',
      ];

      final profileResponse = await widget.client.talk(profileCommand);

      // تحديث القيود
      final limitationCommand = [
        '/user-manager/limitation/set',
        '=.id=$_limitationId',
        '=transfer-limit=${_downloadLimitController.text.isNotEmpty ? "${_downloadLimitController.text}B" : "0B"}',
        '=uptime-limit=${_uptimeLimitController.text.isNotEmpty ? _uptimeLimitController.text : "0s"}',
      ];

      final limitationResponse = await widget.client.talk(limitationCommand);
      print('$limitationResponse');
      if (limitationResponse.isNotEmpty ||
          !profileResponse.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([
        '/user-manager/profile/print',
      ]);

      return response
          .map(
            (profile) => {
              'name': profile['name'],
              'name-for-users': profile['name-for-users'],
              'price': profile['price'],
              'validity': profile['validity'],
            },
          )
          .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: 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: () {},
                        ),
                        _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.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,
                    ),
                  ),
                ],
              ),
              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.people_outline,
                  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),
          ),
        ),
      ),
    );
  }
}


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