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

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

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

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

  String _profileId = '';

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

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

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

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

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

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

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

    switch (index) {
      case 0:
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => RouterDetailsPage(client: widget.client),
          ),
        );
        break;
      case 1:
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => UsersPage(client: widget.client),
          ),
        );
        break;
      case 2:
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(
            builder: (context) => AddHotspotCardsPage(client: widget.client),
          ),
        );
        break;
      case 3:
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Login()),
        );
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Directionality(
      textDirection: TextDirection.rtl,
      child: LayoutBuilder(
        builder: (context, constraints) {
          if (constraints.maxWidth > 800) {
            return _buildDesktopLayout(context);
          } else {
            return _buildMobileLayout(context);
          }
        },
      ),
    );
  }

  Widget _buildDesktopLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      body: Row(
        children: [
          _buildDesktopNavigation(),
          Expanded(
            child: Column(
              children: [
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          _backgroundColor.withOpacity(0.9),
                          _backgroundColor.withOpacity(0.7),
                        ],
                      ),
                    ),
                    child: _buildMainContent(),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

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

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

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

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

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

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

                // حقل حد التحميل
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة التحميل',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _downloadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _downloadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _downloadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),

                SizedBox(height: 12),

                // حقل حد الرفع
                Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: TextField(
                        decoration: InputDecoration(
                          labelText: 'سرعة الرفع',
                          labelStyle: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor.withOpacity(0.8),
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          enabledBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          focusedBorder: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(color: _primaryColor),
                          ),
                          contentPadding: EdgeInsets.symmetric(
                            horizontal: 16,
                            vertical: 14,
                          ),
                          fillColor: _cardColor,
                          filled: true,
                        ),
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                        keyboardType: TextInputType.number,
                        inputFormatters: [
                          FilteringTextInputFormatter.digitsOnly,
                        ],
                        onChanged: (value) {
                          setState(() {
                            _uploadValue = value;
                          });
                        },
                      ),
                    ),
                    SizedBox(width: 8),
                    Expanded(
                      flex: 1,
                      child: DropdownButtonFormField<String>(
                        value: _uploadSpeedUnit,
                        items:
                            ['كيلو', 'ميجا'].map((String unit) {
                              return DropdownMenuItem<String>(
                                value: unit,
                                child: Text(
                                  unit,
                                  style: TextStyle(color: _textColor),
                                ),
                              );
                            }).toList(),
                        onChanged: (String? newValue) {
                          setState(() {
                            _uploadSpeedUnit = newValue!;
                          });
                        },
                        decoration: InputDecoration(
                          filled: true,
                          fillColor: _cardColor,
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(8),
                            borderSide: BorderSide(
                              color: Colors.white.withOpacity(0.2),
                            ),
                          ),
                          contentPadding: EdgeInsets.symmetric(horizontal: 8),
                        ),
                        dropdownColor: _cardColor,
                        style: TextStyle(color: _textColor),
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 16),

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

                    if (_downloadValue.isEmpty || _uploadValue.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('الرجاء إدخال قيم السرعة'),
                          backgroundColor: Colors.red,
                        ),
                      );
                      return;
                    }

                    try {
                      final response = await widget.client.talk([
                        '/ip/hotspot/user/profile/add',
                        '=name=$_profileName',
                        '=rate-limit=${_downloadValue}${_convertToRouterUnit(_downloadSpeedUnit)}/${_uploadValue}${_convertToRouterUnit(_uploadSpeedUnit)}',
                      ]);

                      if (response.isNotEmpty) {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('تم إنشاء البروفايل بنجاح'),
                            backgroundColor: Colors.green,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      } else {
                        ScaffoldMessenger.of(context).showSnackBar(
                          SnackBar(
                            content: Text('حدث خطأ أثناء إنشاء البروفايل'),
                            backgroundColor: Colors.red,
                            behavior: SnackBarBehavior.floating,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                        );
                      }
                    } catch (e) {
                      print('$e');
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('حدث خطأ اثناء انشاء البروفايل'),
                          backgroundColor: Colors.red,
                          behavior: SnackBarBehavior.floating,
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(12),
                          ),
                        ),
                      );
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: _primaryColor,
                    foregroundColor: _textColor,
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    minimumSize: const Size(double.infinity, 50),
                  ),
                  child: const Text('إضافة البروفايل'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

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

        final profiles = snapshot.data!;
        return SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            children: [
              SizedBox(height: 16),
              Container(
                decoration: BoxDecoration(
                  color: Colors.white.withOpacity(0.05),
                  borderRadius: BorderRadius.circular(15),
                  border: Border.all(color: Colors.white.withOpacity(0.1)),
                ),
                padding: EdgeInsets.all(16),
                child: Column(
                  children: [
                    Text(
                      'تعديل إعدادات البروفايل',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        fontSize: 18,
                        fontWeight: FontWeight.bold,
                        color: _textColor,
                      ),
                    ),
                    SizedBox(height: 16),

                    // Dropdown لاختيار البروفايل
                    DropdownButtonFormField<String>(
                      value:
                          profiles.any((p) => p['name'] == _profileName)
                              ? _profileName
                              : null,
                      items:
                          profiles.map((profile) {
                            return DropdownMenuItem<String>(
                              value: profile['name'],
                              child: Text(
                                profile['name'],
                                style: TextStyle(color: _textColor),
                              ),
                            );
                          }).toList(),
                      onChanged: (String? selectedProfile) {
                        if (selectedProfile != null) {
                          _loadProfileData(selectedProfile);
                        }
                      },
                      decoration: InputDecoration(
                        labelText: 'اختر البروفايل للتعديل',
                        labelStyle: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor.withOpacity(0.8),
                        ),
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        enabledBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(
                            color: Colors.white.withOpacity(0.2),
                          ),
                        ),
                        focusedBorder: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(8),
                          borderSide: BorderSide(color: _primaryColor),
                        ),
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 16,
                          vertical: 14,
                        ),
                        fillColor: _cardColor,
                        filled: true,
                      ),
                      dropdownColor: _cardColor,
                      style: TextStyle(color: _textColor),
                    ),
                    SizedBox(height: 12),

                    // حقل حد التحميل
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: downloadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة التحميل',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _downloadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _downloadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),

                    SizedBox(height: 12),

                    // حقل حد الرفع
                    Row(
                      children: [
                        Expanded(
                          flex: 3,
                          child: TextField(
                            controller: uploadController,
                            decoration: InputDecoration(
                              labelText: 'سرعة الرفع',
                              labelStyle: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor.withOpacity(0.8),
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              enabledBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              focusedBorder: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(color: _primaryColor),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16,
                                vertical: 14,
                              ),
                              fillColor: _cardColor,
                              filled: true,
                            ),
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: _textColor,
                            ),
                            keyboardType: TextInputType.number,
                            inputFormatters: [
                              FilteringTextInputFormatter.digitsOnly,
                            ],
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          flex: 1,
                          child: DropdownButtonFormField<String>(
                            value: _uploadSpeedUnit,
                            items:
                                ['كيلو', 'ميجا'].map((String unit) {
                                  return DropdownMenuItem<String>(
                                    value: unit,
                                    child: Text(
                                      unit,
                                      style: TextStyle(color: _textColor),
                                    ),
                                  );
                                }).toList(),
                            onChanged: (String? newValue) {
                              setState(() {
                                _uploadSpeedUnit = newValue!;
                              });
                            },
                            decoration: InputDecoration(
                              filled: true,
                              fillColor: _cardColor,
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(8),
                                borderSide: BorderSide(
                                  color: Colors.white.withOpacity(0.2),
                                ),
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 8,
                              ),
                            ),
                            dropdownColor: _cardColor,
                            style: TextStyle(color: _textColor),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 16),

                    ElevatedButton(
                      onPressed: _updateProfile,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: _primaryColor,
                        foregroundColor: _textColor,
                        padding: const EdgeInsets.symmetric(vertical: 16),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                        minimumSize: const Size(double.infinity, 50),
                      ),
                      child: const Text('تحديث البروفايل'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

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

      if (response.isNotEmpty) {
        final profile = response.first;
        final rateLimit = profile['rate-limit']?.split('/') ?? ['', ''];

        // تحليل قيمة rate-limit
        String downloadValue = '';
        String uploadValue = '';
        String downloadUnit = 'كيلو';
        String uploadUnit = 'كيلو';

        if (rateLimit.length == 2) {
          // تحليل سرعة التحميل
          if (rateLimit[0].contains('M')) {
            downloadValue = rateLimit[0].replaceAll('M', '');
            downloadUnit = 'ميجا';
          } else if (rateLimit[0].contains('K')) {
            downloadValue = rateLimit[0].replaceAll('K', '');
            downloadUnit = 'كيلو';
          }

          // تحليل سرعة الرفع
          if (rateLimit[1].contains('M')) {
            uploadValue = rateLimit[1].replaceAll('M', '');
            uploadUnit = 'ميجا';
          } else if (rateLimit[1].contains('K')) {
            uploadValue = rateLimit[1].replaceAll('K', '');
            uploadUnit = 'كيلو';
          }
        }

        setState(() {
          _profileName = profileName;
          _profileId = profile['.id'] ?? ''; // حفظ معرف البروفايل
          downloadController.text = downloadValue;
          uploadController.text = uploadValue;
          _downloadSpeedUnit = downloadUnit;
          _uploadSpeedUnit = uploadUnit;
        });
      }
    } catch (e) {
      print('Error loading profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحميل بيانات البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

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

    if (downloadController.text.isEmpty || uploadController.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('الرجاء إدخال قيم السرعة'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    try {
      final command = [
        '/ip/hotspot/user/profile/set',
        '=.id=$_profileId',
        '=rate-limit=${downloadController.text}${_convertToRouterUnit(_downloadSpeedUnit)}/${uploadController.text}${_convertToRouterUnit(_uploadSpeedUnit)}',
      ];

      final response = await widget.client.talk(command);

      if (response.isEmpty ||
          !response.any((reply) => reply.containsKey('!trap'))) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم تحديث البروفايل بنجاح'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('حدث خطأ أثناء تحديث البروفايل'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      print('Error updating profile: $e');
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('حدث خطأ أثناء تحديث البروفايل'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

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

      final uniqueProfiles = <Map<String, dynamic>>[];
      final names = <String>{};

      for (var profile in response) {
        if (!names.contains(profile['name'])) {
          names.add(profile['name']!);
          uniqueProfiles.add({
            'name': profile['name'],
            'rate-limit': profile['rate-limit'],
            '.id': profile['.id'],
          });
        }
      }

      return uniqueProfiles;
    } catch (e) {
      debugPrint('Error fetching profiles: $e');
      return [];
    }
  }

  Widget _buildDesktopNavigation() {
    return SingleChildScrollView(
      child: Container(
        width: 280,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(
          color: Colors.white.withOpacity(0.05),
          border: Border(
            right: BorderSide(color: Colors.white.withOpacity(0.1)),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 30),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16),
              child: Row(
                children: [
                  Icon(Icons.speed, color: _primaryColor, size: 28),
                  const SizedBox(width: 10),
                  Text(
                    'إضافة بروفايل',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 30),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // قسم الإدارة الرئيسية
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                      child: Text(
                        'الإدارة الرئيسية',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: Colors.white.withOpacity(0.5),
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    _buildNavItem(
                      icon: Icons.dashboard,
                      title: 'لوحة التحكم',
                      isActive: false,
                      onTap: () {
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder:
                                (context) =>
                                    RouterDetailsPage(client: widget.client),
                          ),
                        );
                      },
                    ),

                    // قسم الهوتسبوت (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة الهوتسبوت',
                      icon: Icons.wifi,
                      initiallyExpanded: isHotspotExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHotspotExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        UsersPage(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: true,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.person_add,
                          title: 'اضافة مستخدم',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 0,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.group_add,
                          title: 'اضافة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => AddHotspotCardsPage(
                                      client: widget.client,
                                      initialTab: 1,
                                    ),
                              ),
                            );
                          },
                        ),
                      ],
                    ),

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

                        _buildNavItem(
                          icon: Icons.assignment,
                          title: 'السجلات',
                          isActive: false,
                          onTap: () {
                            // Navigation code here
                          },
                        ),
                      ],
                    ),

                    // قسم الإعدادات والأدوات (قابل للطي)
                    _buildExpandableSection(
                      title: 'الإعدادات والأدوات',
                      icon: Icons.settings,
                      initiallyExpanded: isSettingsExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isSettingsExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.settings,
                          title: 'إعدادات النظام',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.backup,
                          title: 'النسخ الاحتياطي',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.security,
                          title: 'الأمان',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.cloud,
                          title: 'التحديثات',
                          isActive: false,
                          onTap: () {},
                        ),
                      ],
                    ),

                    // قسم المساعدة والدعم (قابل للطي)
                    _buildExpandableSection(
                      title: 'المساعدة والدعم',
                      icon: Icons.help,
                      initiallyExpanded: isHelpExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isHelpExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.help_outline,
                          title: 'المركز المساعدة',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => HelpDesk(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.feedback,
                          title: 'إرسال ملاحظات',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => SendNotes(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.info_outline,
                          title: 'حول التطبيق',
                          isActive: false,
                          onTap: () {},
                        ),
                        _buildNavItem(
                          icon: Icons.logout,
                          title: 'تسجيل الخروج',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(builder: (context) => Login()),
                            );
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

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

  Widget _buildExpandableSection({
    required String title,
    required IconData icon,
    required List<Widget> children,
    required bool initiallyExpanded,
    required ValueChanged<bool> onExpansionChanged,
  }) {
    return ExpansionTile(
      title: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 8),
        child: Row(
          children: [
            Icon(icon, color: Colors.white.withOpacity(0.7), size: 24),
            const SizedBox(width: 12),
            Text(
              title,
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white.withOpacity(0.7),
                fontSize: 16,
                fontWeight: FontWeight.normal,
              ),
            ),
          ],
        ),
      ),
      childrenPadding: const EdgeInsets.only(left: 16),
      collapsedIconColor: Colors.white.withOpacity(0.7),
      iconColor: Colors.white.withOpacity(0.7),
      initiallyExpanded: initiallyExpanded,
      onExpansionChanged: onExpansionChanged,
      children: children,
    );
  }

  Widget _buildUniversalDrawer() {
    return Drawer(
      backgroundColor: _backgroundColor,
      child: SafeArea(
        child: ListView(
          padding: EdgeInsets.zero,
          children: [
            SizedBox(
              height: 70,
              child: DrawerHeader(
                decoration: BoxDecoration(
                  color: _primaryColor.withOpacity(0.1),
                  border: Border(
                    bottom: BorderSide(color: Colors.white.withOpacity(0.1)),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.network_check,
                          size: 30,
                          color: Colors.white,
                        ),
                        const SizedBox(width: 8),
                        Text(
                          'Micro Panel',
                          style: const TextStyle(
                            fontFamily: 'Tajawal',
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),

            // Main Navigation Items
            _buildUniversalDrawerItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) =>
                            RouterDetailsPage(client: widget.client),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),

            // Hotspot Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.wifi, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة الهوتسبوت',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              initiallyExpanded: true,
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UsersPage(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.people,
                  title: 'البروفايل',
                  onTap: () {},
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.person_add,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.group_add,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddHotspotCardsPage(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),

            // User Manager Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(
                    Icons.manage_accounts,
                    color: Colors.white.withOpacity(0.7),
                  ),
                  const SizedBox(width: 12),
                  Text(
                    'إدارة اليوزر مانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),

              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.people_outline,
                  title: 'قائمة المستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerUserList(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.speed,
                  title: 'البروفايل',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerProfile(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.payment_rounded,
                  title: 'إضافة مستخدم',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 0,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.credit_score,
                  title: 'إضافة مستخدمين',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                AddUserManagerCards(
                                  client: widget.client,
                                  initialTab: 1,
                                ),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                UserManagerSession(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
              ],
            ),

            // Settings Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.settings, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'الإعدادات والأدوات',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.settings,
                  title: 'إعدادات النظام',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.backup,
                  title: 'النسخ الاحتياطي',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.security,
                  title: 'الأمان',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.cloud,
                  title: 'التحديثات',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),

            // Help Section
            ExpansionTile(
              title: Row(
                children: [
                  Icon(Icons.help, color: Colors.white.withOpacity(0.7)),
                  const SizedBox(width: 12),
                  Text(
                    'المساعدة والدعم',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white.withOpacity(0.7),
                      fontSize: 16,
                    ),
                  ),
                ],
              ),
              children: [
                _buildUniversalDrawerItem(
                  icon: Icons.help_outline,
                  title: 'المركز المساعدة',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                HelpDesk(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      PageRouteBuilder(
                        pageBuilder:
                            (context, animation, secondaryAnimation) =>
                                SendNotes(client: widget.client),
                        transitionsBuilder: (
                          context,
                          animation,
                          secondaryAnimation,
                          child,
                        ) {
                          const begin = Offset(0.0, 1.0);
                          const end = Offset.zero;
                          const curve = Curves.ease;
                          var tween = Tween(
                            begin: begin,
                            end: end,
                          ).chain(CurveTween(curve: curve));
                          return SlideTransition(
                            position: animation.drive(tween),
                            child: child,
                          );
                        },
                        transitionDuration: const Duration(milliseconds: 300),
                      ),
                    );
                  },
                ),
                _buildUniversalDrawerItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  onTap: () {
                    // TODO: Add navigation
                  },
                ),
              ],
            ),

            const Divider(color: Colors.white24),

            // Logout Item
            _buildUniversalDrawerItem(
              icon: Icons.logout,
              title: 'تسجيل خروج',
              color: Colors.red,
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  PageRouteBuilder(
                    pageBuilder:
                        (context, animation, secondaryAnimation) => Login(),
                    transitionsBuilder: (
                      context,
                      animation,
                      secondaryAnimation,
                      child,
                    ) {
                      const begin = Offset(0.0, 1.0);
                      const end = Offset.zero;
                      const curve = Curves.ease;
                      var tween = Tween(
                        begin: begin,
                        end: end,
                      ).chain(CurveTween(curve: curve));
                      return SlideTransition(
                        position: animation.drive(tween),
                        child: child,
                      );
                    },
                    transitionDuration: const Duration(milliseconds: 300),
                  ),
                );
              },
            ),
          ],
        ),
      ),
    );
  }

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

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

  Widget _AppBarActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onPressed,
    required Color color,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 4),
      child: Tooltip(
        message: label,
        child: IconButton(
          icon: Icon(icon, size: 20),
          color: color,
          onPressed: onPressed,
          style: IconButton.styleFrom(
            backgroundColor: color.withOpacity(0.1),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8),
            ),
            padding: EdgeInsets.all(8),
          ),
        ),
      ),
    );
  }
}