اريد ان يظهر file manager لتحديد مكان حفظ الملف في الهاتف 
ملاحظة اعطيني الجزء السابق والجزء المراد استبدالة بة
للعلم الكود
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:intl/intl.dart' as intl;
import 'package:micro_panel/AboutApp.dart';
import 'package:micro_panel/AddHotspotUser.dart';
import 'package:micro_panel/AddUserManagerUser.dart';
import 'package:micro_panel/HelpDesk.dart';
import 'package:micro_panel/HomePage.dart';
import 'package:micro_panel/HotspotProfile.dart';
import 'package:micro_panel/Login.dart';
import 'package:micro_panel/SendNotes.dart';
import 'package:micro_panel/Transmitters.dart';
import 'package:micro_panel/UserManagerProfile.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/UserManagerUserList.dart';
import 'package:micro_panel/backupSN.dart';
import 'package:micro_panel/free_rebiuld.dart';
import 'package:micro_panel/hotspotUserList.dart';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
import 'package:router_os_client/router_os_client.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:file_picker/file_picker.dart';

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

  @override
  State<UserManagerSales> createState() => _UserManagerSalesState();
}

class _UserManagerSalesState extends State<UserManagerSales> {
  Color _primaryColor = const Color(0xFF3B82F6);
  Color _backgroundColor = const Color(0xFF0A192F);
  Color _cardColor = const Color(0xFF172A46);
  Color _textColor = Colors.white;
  int _currentIndex = 0;

  final ValueNotifier<bool> _isLoadingNotifier = ValueNotifier(false);
  final ValueNotifier<String?> _errorNotifier = ValueNotifier(null);

  List<Map<String, dynamic>> _filteredSessions = [];
  final ValueNotifier<String?> _loadingMessageNotifier = ValueNotifier(null);

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

  late MicroPanelSales _MicroPanelSales;

  @override
  void initState() {
    super.initState();
    // تعيين القيم الافتراضية للتواريخ والأوقات
    final now = DateTime.now();

    _startDate = now.subtract(Duration(days: 1));
    _endDate = now;

    _startTime = TimeOfDay(hour: 0, minute: 0);
    _endTime = TimeOfDay(hour: now.hour, minute: now.minute);

    _MicroPanelSales = MicroPanelSales(client: widget.client);
    _connectAndFetchData().then((_) {
      setState(() {
        _filterDataByDateRange();
      });
    });
  }

  pw.Widget _tableCell(dynamic text) => pw.Padding(
    padding: const pw.EdgeInsets.all(5),
    child: pw.Text(text.toString(), textAlign: pw.TextAlign.center),
  );

  Future<void> _generatePdf() async {
    try {
      _isLoadingNotifier.value = true;

      final pdf = pw.Document();

      final userCount = _filteredSessions.length;
      final totalPrice = _filteredSessions.fold(0, (sum, user) {
        final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
        return sum + (price ~/ 100);
      });

      final dateFormat = intl.DateFormat('yyyy/MM/dd HH:mm');
      final now = DateTime.now();

      final startDateTime = DateTime(
        _startDate!.year,
        _startDate!.month,
        _startDate!.day,
        _startTime!.hour,
        _startTime!.minute,
      );
      final endDateTime = DateTime(
        _endDate!.year,
        _endDate!.month,
        _endDate!.day,
        _endTime!.hour,
        _endTime!.minute,
      );

      final headerWidgets = <pw.Widget>[
        pw.Header(
          level: 0,
          child: pw.Row(
            mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
            children: [
              pw.Text(
                'تقرير اليوزر مانجر',
                style: pw.TextStyle(
                  fontSize: 24,
                  fontWeight: pw.FontWeight.bold,
                ),
              ),
              pw.Text(
                dateFormat.format(now),
                style: pw.TextStyle(fontSize: 12),
              ),
            ],
          ),
        ),
        pw.SizedBox(height: 10),
        pw.Text(
          'الفترة الزمنية: ${dateFormat.format(startDateTime)} - ${dateFormat.format(endDateTime)}',
          style: pw.TextStyle(fontSize: 12),
        ),
        pw.Text(
          'عدد المستخدمين: $userCount',
          style: pw.TextStyle(fontSize: 12),
        ),
        pw.Text('الإجمالي: $totalPrice', style: pw.TextStyle(fontSize: 12)),
        pw.SizedBox(height: 20),
      ];

      final tableHeaderRow = pw.TableRow(
        decoration: pw.BoxDecoration(color: PdfColor.fromHex('#3B82F6')),
        children: [
          _tableHeader('اسم المستخدم'),
          _tableHeader('السعر'),
          _tableHeader('أول تسجيل دخول'),
          _tableHeader('قطعة البث'),
        ],
      );

      final tableRows =
          _filteredSessions.asMap().entries.map((entry) {
            final index = entry.key;
            final user = entry.value;
            final isEven = index % 2 == 0;

            return pw.TableRow(
              decoration: pw.BoxDecoration(
                color: isEven ? PdfColors.grey100 : PdfColors.white,
              ),
              children: [
                _tableCell(user['username']?.toString() ?? 'غير معروف'),
                _tableCell(
                  user['price'] != null
                      ? (int.tryParse(user['price'].toString()) ?? 0) ~/ 100
                      : 0,
                ),
                _tableCell(
                  user['from-time'] != null
                      ? _formatMikrotikDateTimeToArabic(
                        user['from-time'].toString(),
                      )
                      : 'غير معروف',
                ),
                _tableCell(user['nas-port-id']?.toString() ?? 'غير معروف'),
              ],
            );
          }).toList();
      Future<pw.Font> _loadArabicFont() async {
        try {
          // تحميل الخط من الأصول المحلية
          final fontData = await rootBundle.load(
            'assets/fonts/Tajawal-Regular.ttf',
          );
          final font = pw.Font.ttf(fontData);
          return font;
        } catch (e) {
          // استخدام خط بديل في حالة الخطأ
          return pw.Font.courier();
        }
      }

      pdf.addPage(
        pw.MultiPage(
          pageFormat: PdfPageFormat.a4,
          textDirection: pw.TextDirection.rtl,
          theme: pw.ThemeData.withFont(
            base: await _loadArabicFont(),
            bold:
                await _loadArabicFont(), // يمكنك تحميل خط bold منفصل إذا كان متوفراً
          ),
          build:
              (pw.Context context) => [
                ...headerWidgets,
                pw.Table(
                  border: pw.TableBorder.all(
                    color: PdfColors.grey400,
                    width: 0.5,
                  ),
                  tableWidth: pw.TableWidth.max,
                  defaultVerticalAlignment:
                      pw.TableCellVerticalAlignment.middle,
                  children: [tableHeaderRow, ...tableRows],
                ),
              ],
        ),
      );

      final tempDir = await getTemporaryDirectory();
      final tempPath = '${tempDir.path}/user_manager_report.pdf';
      final tempFile = File(tempPath);
      await tempFile.writeAsBytes(await pdf.save());

      // اختيار مكان الحفظ باستخدام FilePicker
      final String? savePath = await FilePicker.platform.saveFile(
        dialogTitle: 'حفظ تقرير اليوزر مانجر',
        fileName:
            'تقرير_اليوزر_مانجر_${DateTime.now().millisecondsSinceEpoch}.pdf',
        allowedExtensions: ['pdf'],
        type: FileType.custom,
      );

      if (savePath != null) {
        final savedFile = File(savePath);
        await tempFile.copy(savePath);
        await tempFile.delete();

        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('تم حفظ التقرير بنجاح')));

          // فتح الملف باستخدام تطبيق عرض PDF
          try {
            await OpenFile.open(savedFile.path);
          } catch (e) {
            if (mounted) {
              ScaffoldMessenger.of(
                context,
              ).showSnackBar(SnackBar(content: Text('تعذر فتح الملف')));
            }
          }
        }
      } else {
        await tempFile.delete();
        if (mounted) {
          ScaffoldMessenger.of(
            context,
          ).showSnackBar(SnackBar(content: Text('تم إلغاء عملية الحفظ')));
        }
      }
    } catch (e) {
      debugPrint('Error generating PDF: $e');
      if (mounted) {
        ScaffoldMessenger.of(
          context,
        ).showSnackBar(SnackBar(content: Text('حدث خطأ أثناء إنشاء التقرير')));
      }
    } finally {
      _isLoadingNotifier.value = false;
    }
  }

  Future<void> _connectAndFetchData() async {
    try {
      _isLoadingNotifier.value = true;
      _loadingMessageNotifier.value = 'جاري اعداد التقارير ...';

      // عرض بيانات الاتصال قبل المحاولة
      print('''
    جاري الاتصال بالراوتر باستخدام:
    - العنوان: ${_MicroPanelSales.host}
    - المنفذ: ${_MicroPanelSales.port}
    - اسم المستخدم: ${_MicroPanelSales.user}
    - كلمة المرور: ${_MicroPanelSales.pass.replaceAll(RegExp(r'.'), '*')}  // إخفاء كلمة المرور
    ''');

      await _MicroPanelSales.connect();
      print('✅ تم الاتصال بالراوتر بنجاح');

      _fetchDataFromRouter();
    } catch (e) {
      _errorNotifier.value = 'فشل الاتصال بالراوتر';
      _isLoadingNotifier.value = false;
      print('❌ فشل الاتصال: $e');
    } finally {
      _isLoadingNotifier.value = false;
      _loadingMessageNotifier.value = null;
    }
  }

  pw.Widget _tableHeader(String text) => pw.Padding(
    padding: const pw.EdgeInsets.all(6),
    child: pw.Text(
      text,
      style: pw.TextStyle(
        fontWeight: pw.FontWeight.bold,
        color: PdfColors.white,
      ),
      textAlign: pw.TextAlign.center,
    ),
  );

  // متغيرات جديدة لتخزين التواريخ
  DateTime? _startDate;
  DateTime? _endDate;
  TimeOfDay? _startTime;
  TimeOfDay? _endTime;
  List<Map<String, dynamic>> _allSessions = []; // لتخزين جميع البيانات

  Future<void> _fetchDataFromRouter() async {
    final routerVersion = await _getRouterVersion();
    final isVersion7 = routerVersion >= 7;
    try {
      _isLoadingNotifier.value = true;
      _loadingMessageNotifier.value = 'جاري اعداد التقارير ...';
      _errorNotifier.value = null;
      print('بدء محاولة الجلب');

      // 1. جلب قائمة المستخدمين وتخزينها في مصفوفة أولية
      Future<List<List<String>>> fetchDataFromNewConnection(
        List<String> command,
      ) async {
        final tempClient = MicroPanelSales(client: widget.client);
        await tempClient.connect();
        final response = await tempClient.sendSentenceWithResponse(command);
        tempClient.disconnect();
        return response;
      }

      final futures = <Future<List<List<String>>>>[
        fetchDataFromNewConnection([
          isVersion7
              ? ' user-manager/user-profile/print'
              : '/tool/user-manager/user/print',
          if (!isVersion7) '?download-used',
          isVersion7 ? '=.proplist=user' : '=.proplist=username',
        ]),
        fetchDataFromNewConnection([
          '/tool/user-manager/payment/print',
          '=.proplist=user,price,time',
        ]),
        fetchDataFromNewConnection([
          '/tool/user-manager/session/print',
          '=.proplist=user,nas-port-id,from-time',
        ]),
      ];

      final responses = await Future.wait(futures);

      final usersResponse = responses[0];
      final paymentsResponse = responses[1];
      final sessionsResponse = responses[2];

      print('استجابة المستخدمين: $usersResponse');
      print('استجابة المدفوعات: $paymentsResponse');
      print('استجابة الجلسات: $sessionsResponse');

      List<Map<String, dynamic>> userList = [];
      for (var sentence in usersResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> userData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                userData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (userData.isNotEmpty && userData.containsKey('username')) {
            userList.add(userData);
          }
        }
      }
      print('تم جلب ${userList.length} مستخدم');

      List<Map<String, dynamic>> allPayments = [];
      for (var sentence in paymentsResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> paymentData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                paymentData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (paymentData.isNotEmpty && paymentData.containsKey('user')) {
            allPayments.add(paymentData);
          }
        }
      }

      List<Map<String, dynamic>> allSessions = [];
      for (var sentence in sessionsResponse) {
        if (sentence.isNotEmpty && sentence.first == '!re') {
          Map<String, dynamic> sessionData = {};
          for (var token in sentence.skip(1)) {
            if (token.startsWith('=')) {
              final parts = token.substring(1).split('=');
              if (parts.length >= 2) {
                sessionData[parts[0]] = parts.sublist(1).join('=');
              }
            }
          }
          if (sessionData.isNotEmpty && sessionData.containsKey('user')) {
            allSessions.add(sessionData);
          }
        }
      }

      // 4. ربط البيانات من المصفوفات الثلاث مع بعضها البعض
      List<Map<String, dynamic>> allData = [];

      for (var user in userList) {
        final username = user['username'];
        if (username == null) continue;

        try {
          // تصفية مدفوعات هذا المستخدم
          final userPayments =
              allPayments.where((p) => p['user'] == username).toList();

          // تصفية جلسات هذا المستخدم
          final userSessions =
              allSessions.where((s) => s['user'] == username).toList();

          // العثور على الجلسة ذات أقل تاريخ تسجيل دخول (from-time)
          Map<String, dynamic>? earliestSession;
          DateTime? earliestDate;

          for (final session in userSessions) {
            final fromTimeStr = session['from-time'] ?? '';
            final parsedDate = _parseMikrotikDateTime(fromTimeStr);
            if (parsedDate != null) {
              if (earliestDate == null || parsedDate.isBefore(earliestDate)) {
                earliestDate = parsedDate;
                earliestSession = session;
              }
            }
          }

          // إذا لم نجد أي جلسة صالحة، نستخدم بيانات افتراضية
          if (earliestSession == null) {
            earliestSession = {
              'from-time': 'غير معروف',
              'nas-port-id': 'غير معروف',
            };
            earliestDate = null;
          }

          // دمج البيانات لكل مستخدم مع أول تسجيل دخول
          allData.add({
            'username': username,
            'price':
                userPayments.isNotEmpty
                    ? userPayments.last['price'] ?? '0'
                    : '0',
            'from-time': earliestSession['from-time'] ?? 'غير معروف',
            'nas-port-id': earliestSession['nas-port-id'] ?? 'غير معروف',
            'parsed-time': earliestDate,
          });
        } catch (e) {
          debugPrint('Error processing data for user $username: $e');
          // إضافة بيانات أساسية حتى لو فشل جلب بعض البيانات
          allData.add({
            'username': username,
            'price': '0',
            'from-time': 'غير معروف',
            'nas-port-id': 'غير معروف',
            'parsed-time': null,
          });
        }
      }

      // 5. تطبيق الفلترة على البيانات المدمجة
      setState(() {
        _allSessions = allData;
      });
      _filterDataByDateRange();

      _isLoadingNotifier.value = false;
    } catch (e, stackTrace) {
      _errorNotifier.value = 'حدث خطأ أثناء جلب البيانات';
      _isLoadingNotifier.value = false;
      debugPrint('Error in _fetchDataFromRouter: $e');
      debugPrint('Stack trace: $stackTrace');

      // محاولة إعادة الاتصال
      try {
        await _MicroPanelSales.connect();
      } catch (e) {
        debugPrint('Failed to reconnect: $e');
      }
    }
  }

  // دالة لتصفية البيانات حسب الفترة الزمنية
  void _filterDataByDateRange() {
    if (_startDate == null ||
        _endDate == null ||
        _startTime == null ||
        _endTime == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('الرجاء تحديد الفترة الزمنية أولاً')),
      );

      return;
    }

    // دمج التاريخ والوقت
    final startDateTime = DateTime(
      _startDate!.year,
      _startDate!.month,
      _startDate!.day,
      _startTime!.hour,
      _startTime!.minute,
    );

    final endDateTime = DateTime(
      _endDate!.year,
      _endDate!.month,
      _endDate!.day,
      _endTime!.hour,
      _endTime!.minute,
    );

    setState(() {
      _filteredSessions =
          _allSessions.where((session) {
            final sessionTime = session['parsed-time'];
            if (sessionTime == null) return false;

            return sessionTime.isAfter(startDateTime) &&
                sessionTime.isBefore(endDateTime);
          }).toList();
    });
  }

  // دالة لاختيار التاريخ
  Future<void> _selectDate(BuildContext context, bool isStartDate) async {
    final DateTime? picked = await showDatePicker(
      context: context,
      initialDate: DateTime.now(),
      firstDate: DateTime(2000),
      lastDate: DateTime(2101),
    );
    if (picked != null) {
      setState(() {
        if (isStartDate) {
          _startDate = picked;
        } else {
          _endDate = picked;
        }
      });

      if (_startDate != null &&
          _endDate != null &&
          _startTime != null &&
          _endTime != null) {
        _filterDataByDateRange();
      }
    }
  }

  // دالة لاختيار الوقت
  Future<void> _selectTime(BuildContext context, bool isStartTime) async {
    final TimeOfDay? picked = await showTimePicker(
      context: context,
      initialTime: TimeOfDay.now(),
    );
    if (picked != null) {
      setState(() {
        if (isStartTime) {
          _startTime = picked;
        } else {
          _endTime = picked;
        }
      });
      // محاولة تطبيق الفلترة إذا كانت البيانات كاملة
      if (_startDate != null &&
          _endDate != null &&
          _startTime != null &&
          _endTime != null) {
        _filterDataByDateRange();
      }
    }
  }

  // إضافة واجهة اختيار التاريخ والوقت في ويدجت البناء
  Widget _buildDateRangeSelector() {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 16,
        vertical: MediaQuery.of(context).size.width > 600 ? 24 : 16,
      ),
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(12),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final isWideScreen = constraints.maxWidth > 600;

          return Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // عنوان القسم
              Row(
                children: [
                  Icon(Icons.calendar_today, color: Colors.white70, size: 20),
                  SizedBox(width: 8),
                  Text(
                    'تحديد النطاق الزمني',
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: isWideScreen ? 18 : 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
              SizedBox(height: 16),

              // عرض أفقي للشاشات الكبيرة وعمودي للصغيرة
              isWideScreen ? _buildWideLayout() : _buildMobileLayoutTimer(),

              SizedBox(height: 16),

              // زر التطبيق
              SizedBox.shrink(),
            ],
          );
        },
      ),
    );
  }

  Widget _buildWideLayout() {
    return Row(
      children: [
        Expanded(child: _buildDatePicker(true)), // تاريخ البداية
        SizedBox(width: 16),
        Center(child: Icon(Icons.arrow_forward, color: Colors.white54)),
        SizedBox(width: 16),
        Expanded(child: _buildDatePicker(false)), // تاريخ النهاية
      ],
    );
  }

  Widget _buildMobileLayoutTimer() {
    return Column(
      children: [
        _buildDatePicker(true), // تاريخ البداية
        SizedBox(height: 12),

        _buildDatePicker(false), // تاريخ النهاية
      ],
    );
  }

  Widget _buildDatePicker(bool isStartDate) {
    final bool isMobile = MediaQuery.of(context).size.width < 600;

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        if (!isMobile)
          Text(
            isStartDate ? 'من تاريخ:' : 'إلى تاريخ:',
            style: TextStyle(color: Colors.white70, fontSize: 13), // أقل قليلاً
          ),
        SizedBox(height: isMobile ? 2 : 6), // قلل الارتفاع

        if (isMobile)
          Material(
            color: Colors.transparent,
            child: InkWell(
              onTap: () async {
                await _selectDate(context, isStartDate);
                await _selectTime(context, isStartDate);
              },
              child: Container(
                padding: EdgeInsets.all(8), // قلل الـ padding
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.2),
                  border: Border.all(color: Colors.white24),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  children: [
                    Icon(Icons.calendar_month, color: Colors.white70, size: 20),
                    SizedBox(width: 6),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            isStartDate ? 'تاريخ البداية' : 'تاريخ النهاية',
                            style: TextStyle(
                              color: Colors.white70,
                              fontSize: 11,
                            ),
                          ),
                          SizedBox(height: 1),
                          Text(
                            isStartDate
                                ? (_startDate != null
                                    ? '${intl.DateFormat('yyyy/MM/dd').format(_startDate!)} ${_startTime?.format(context) ?? ''}'
                                    : 'اختر التاريخ والوقت')
                                : (_endDate != null
                                    ? '${intl.DateFormat('yyyy/MM/dd').format(_endDate!)} ${_endTime?.format(context) ?? ''}'
                                    : 'اختر التاريخ والوقت'),
                            style: TextStyle(color: Colors.white, fontSize: 13),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          )
        else
          Column(
            children: [
              Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => _selectDate(context, isStartDate),
                  child: Container(
                    padding: EdgeInsets.all(8), // قلل الـ padding
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                      border: Border.all(color: Colors.white24),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.calendar_month,
                          color: Colors.white70,
                          size: 20,
                        ),
                        SizedBox(width: 6),
                        Text(
                          isStartDate
                              ? (_startDate != null
                                  ? intl.DateFormat(
                                    'yyyy/MM/dd',
                                  ).format(_startDate!)
                                  : 'اختر التاريخ')
                              : (_endDate != null
                                  ? intl.DateFormat(
                                    'yyyy/MM/dd',
                                  ).format(_endDate!)
                                  : 'اختر التاريخ'),
                          style: TextStyle(color: Colors.white, fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
              SizedBox(height: 6),
              Material(
                color: Colors.transparent,
                child: InkWell(
                  onTap: () => _selectTime(context, isStartDate),
                  child: Container(
                    padding: EdgeInsets.all(8), // قلل الـ padding
                    decoration: BoxDecoration(
                      color: Colors.black.withOpacity(0.2),
                      border: Border.all(color: Colors.white24),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Row(
                      children: [
                        Icon(
                          Icons.access_time,
                          color: Colors.white70,
                          size: 20,
                        ),
                        SizedBox(width: 6),
                        Text(
                          isStartDate
                              ? (_startTime != null
                                  ? _startTime!.format(context)
                                  : 'اختر الوقت')
                              : (_endTime != null
                                  ? _endTime!.format(context)
                                  : 'اختر الوقت'),
                          style: TextStyle(color: Colors.white, fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
      ],
    );
  }

  DateTime? _parseMikrotikDateTime(String mikDate) {
    try {
      // تحقق من أن النص ليس فارغاً
      if (mikDate.isEmpty) return null;

      // فصل الجزء الزمني عن التاريخ
      final parts = mikDate.split(' ');
      if (parts.length != 2) return null;

      final datePart = parts[0].trim(); // الجزء التاريخي
      final timePart = parts[1].trim(); // الجزء الزمني

      // تحليل التاريخ
      final dateComponents = datePart.split('/');
      if (dateComponents.length != 3) return null;

      // معالجة الشهر
      final monthStr = dateComponents[0].toLowerCase();
      final months = {
        'jan': 1,
        'feb': 2,
        'mar': 3,
        'apr': 4,
        'may': 5,
        'jun': 6,
        'jul': 7,
        'aug': 8,
        'sep': 9,
        'oct': 10,
        'nov': 11,
        'dec': 12,
      };

      final month = months[monthStr];
      if (month == null) return null;

      // معالجة اليوم والسنة
      final day = int.tryParse(dateComponents[1]) ?? 1;
      final year = int.tryParse(dateComponents[2]) ?? DateTime.now().year;

      // تحليل الوقت
      final timeComponents = timePart.split(':');
      if (timeComponents.length < 2 || timeComponents.length > 3) return null;

      final hour = int.tryParse(timeComponents[0]) ?? 0;
      final minute = int.tryParse(timeComponents[1]) ?? 0;
      final second =
          timeComponents.length == 3 ? int.tryParse(timeComponents[2]) ?? 0 : 0;

      // إنشاء كائن DateTime مع التحقق من الصحة
      final dateTime = DateTime(year, month, day, hour, minute, second);

      // التحقق من أن التاريخ صحيح (لحالات مثل 31 فبراير)
      if (dateTime.month != month || dateTime.day != day) {
        return null;
      }

      return dateTime;
    } catch (e) {
      debugPrint('Failed to parse MikroTik date: $mikDate, error: $e');
      return null;
    }
  }

  /// دالة التنسيق إلى اللغة العربية
  String _formatMikrotikDateTimeToArabic(String mikDate) {
    try {
      final parsedDate = _parseMikrotikDateTime(mikDate);
      if (parsedDate == null) return mikDate;

      final dateFormat = intl.DateFormat('d-M-yyyy h:mm a', 'ar');
      return dateFormat
          .format(parsedDate)
          .replaceAll('AM', 'صباحاً')
          .replaceAll('PM', 'مساءً');
    } catch (e) {
      return mikDate;
    }
  }

  Widget _buildDataTable() {
    return LayoutBuilder(
      builder: (context, constraints) {
        // إذا لم يكن هناك بيانات
        if (_filteredSessions.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.people_outline,
                  size: 64,
                  color: Colors.white.withOpacity(0.3),
                ),
                SizedBox(height: 16),
                Text(
                  'لا يوجد مستخدمين',
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.5),
                    fontSize: 18,
                  ),
                ),
              ],
            ),
          );
        }

        // للشاشات الكبيرة (أعرض من 600 بكسل)
        if (constraints.maxWidth > 600) {
          return SingleChildScrollView(
            scrollDirection: Axis.vertical,
            child: Container(
              width: double.infinity,
              padding: EdgeInsets.all(8),
              child: DataTable(
                columnSpacing: 20,
                horizontalMargin: 12,
                headingRowColor: MaterialStateProperty.resolveWith<Color>(
                  (Set<MaterialState> states) => _primaryColor.withOpacity(0.2),
                ),
                columns: const [
                  DataColumn(
                    label: Text(
                      'اسم المستخدم',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'السعر',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'أول تسجيل دخول',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  DataColumn(
                    label: Text(
                      'قطعة البث',
                      style: TextStyle(
                        color: Colors.white,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
                rows:
                    _filteredSessions.map((data) {
                      return DataRow(
                        cells: [
                          DataCell(
                            Text(
                              data['username']?.toString() ?? 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              data['price'] != null
                                  ? (int.parse(data['price'].toString()) ~/ 100)
                                      .toString()
                                  : 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              _formatMikrotikDateTimeToArabic(
                                data['from-time']?.toString() ?? 'غير معروف',
                              ),
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          DataCell(
                            Text(
                              data['nas-port-id']?.toString() ?? 'غير معروف',
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                        ],
                      );
                    }).toList(),
              ),
            ),
          );
        }
        // للشاشات الصغيرة (الهواتف)
        else {
          return ListView.builder(
            itemCount: _filteredSessions.length,
            itemBuilder: (context, index) {
              final data = _filteredSessions[index];
              return Card(
                margin: EdgeInsets.symmetric(vertical: 4, horizontal: 8),
                color: _cardColor,
                child: Padding(
                  padding: EdgeInsets.all(12),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      _buildMobileTableRow(
                        'اسم المستخدم',
                        data['username']?.toString() ?? 'غير معروف',
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'السعر',
                        data['price'] != null
                            ? (int.parse(data['price'].toString()) ~/ 100)
                                .toString()
                            : 'غير معروف',
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'أول تسجيل دخول',
                        _formatMikrotikDateTimeToArabic(
                          data['from-time']?.toString() ?? 'غير معروف',
                        ),
                      ),
                      Divider(color: Colors.white24),
                      _buildMobileTableRow(
                        'قطعة البث',
                        data['nas-port-id']?.toString() ?? 'غير معروف',
                      ),
                    ],
                  ),
                ),
              );
            },
          );
        }
      },
    );
  }

  // دالة مساعدة لعرض الصفوف في الوضع الموبايل
  Widget _buildMobileTableRow(String title, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          title,
          style: TextStyle(
            color: _primaryColor,
            fontWeight: FontWeight.bold,
            fontSize: 14,
          ),
        ),
        Text(value, style: TextStyle(color: Colors.white, fontSize: 14)),
      ],
    );
  }

  String _formatBytes(int bytes) {
    if (bytes <= 0) return "0 B";
    const suffixes = ["B", "KB", "MB", "GB", "TB"];
    var i = (log(bytes) / log(1024)).floor();
    return '${(bytes / pow(1024, i)).toStringAsFixed(2)} ${suffixes[i]}';
  }

  // دالة مساعدة لتحويل صيغة MikroTik "Jul/26/2025 13:59:22" إلى DateTime

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

      if (await file.exists()) {
        final content = await file.readAsString();
        final jsonData = jsonDecode(content);
        return int.tryParse(jsonData['router_version'].toString()) ?? 6;
      }
      return 6;
    } catch (e) {
      debugPrint('Error reading version file: $e');
      return 6;
    }
  }

  @override
  void dispose() {
    super.dispose();
    _loadingMessageNotifier.dispose();
    _isLoadingNotifier.dispose();
  }

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

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

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

  Widget _buildMobileLayout(BuildContext context) {
    // حساب عدد المستخدمين وإجمالي السعر
    final userCount = _filteredSessions.length;
    final totalPrice = _filteredSessions.fold(0, (sum, user) {
      final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
      return sum + (price ~/ 100); // القسمة على 100 لتحويل السعر
    });

    return Scaffold(
      backgroundColor: _backgroundColor,
      drawer: _buildUniversalDrawer(),
      appBar: AppBar(
        title: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            const Text(
              'تقارير اليوزر مانجر',
              style: TextStyle(
                fontFamily: 'Tajawal',
                color: Colors.white,
                fontSize: 17,
              ),
            ),
            if (userCount > 0)
              Text(
                'المستخدمين: $userCount | الإجمالي: $totalPrice',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: Colors.white70,
                  fontSize: 12,
                ),
              ),
          ],
        ),
        backgroundColor: _backgroundColor,
        centerTitle: true,
        elevation: 0,
        leading: Builder(
          builder:
              (context) => IconButton(
                icon: Icon(Icons.menu_rounded, color: _textColor),
                onPressed: () => Scaffold.of(context).openDrawer(),
              ),
        ),
        actions: [
          if (_filteredSessions.isNotEmpty)
            IconButton(
              icon: Icon(Icons.picture_as_pdf, color: _primaryColor),
              onPressed:
                  _isLoadingNotifier.value
                      ? null
                      : () async {
                        _loadingMessageNotifier.value =
                            'جاري تحضير ملف التقرير ...';
                        _isLoadingNotifier.value = true;
                        try {
                          await _generatePdf();
                        } finally {
                          _isLoadingNotifier.value = false;
                          _loadingMessageNotifier.value = null;
                        }
                      },
              tooltip: 'تصدير إلى PDF',
            ),
        ],
      ),
      body: _buildMainContent(showHeader: false),
    );
  }

  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.bar_chart, color: _primaryColor, size: 28),
                  const SizedBox(width: 10),
                  Text(
                    'تقارير اليوزرمانجر',
                    style: TextStyle(
                      fontFamily: 'Tajawal',
                      color: Colors.white,
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 30),
            Expanded(
              child: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // قسم الإدارة الرئيسية
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                      child: Text(
                        'الإدارة الرئيسية',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: Colors.white.withOpacity(0.5),
                          fontSize: 12,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    _buildNavItem(
                      icon: Icons.dashboard,
                      title: 'لوحة التحكم',
                      isActive: false,
                      onTap: () {
                        Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                            builder:
                                (context) =>
                                    RouterDetailsPage(client: widget.client),
                          ),
                        );
                      },
                    ),

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

                    // قسم اليوزر مانجر (قابل للطي)
                    _buildExpandableSection(
                      title: 'إدارة اليوزر مانجر',
                      icon: Icons.manage_accounts,
                      initiallyExpanded: isUserManagerExpanded,
                      onExpansionChanged: (expanded) {
                        setState(() {
                          isUserManagerExpanded = expanded;
                        });
                      },
                      children: [
                        _buildNavItem(
                          icon: Icons.people_outline,
                          title: 'قائمة المستخدمين',
                          isActive: false,
                          onTap: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (_) => UserManagerUserList(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.speed,
                          title: 'البروفايل',
                          isActive: 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: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) => UserManagerSession(
                                      client: widget.client,
                                    ),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.bar_chart,
                          title: 'التقارير',
                          isActive: true,
                          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: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        FreeRebuildDB(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.backup,
                          title: 'النسخ الاحتياطي',
                          isActive: false,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        backupSN(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _buildNavItem(
                          icon: Icons.devices_other_outlined,
                          title: 'قطع البث',
                          isActive: false,
                          onTap: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder:
                                    (context) =>
                                        Transmitters(client: widget.client),
                              ),
                            );
                          },
                        ),
                      ],
                    ),

                    // قسم المساعدة والدعم (قابل للطي)
                    _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: () {
                            Navigator.pushReplacement(
                              context,
                              MaterialPageRoute(
                                builder: (_) => AboutApp(client: widget.client),
                              ),
                            );
                          },
                        ),
                        _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: SingleChildScrollView(
          child: Column(
            children: [
              // Stylish Drawer Header
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(
                  horizontal: 20,
                  vertical: 25,
                ),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      _primaryColor.withOpacity(0.9),
                      _primaryColor.withOpacity(0.6),
                    ],
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.2),
                      blurRadius: 6,
                      offset: Offset(0, 3),
                    ),
                  ],
                  borderRadius: BorderRadius.vertical(
                    bottom: Radius.circular(24),
                  ),
                ),
                child: Row(
                  children: [
                    // Logo or Icon Container
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Colors.white.withOpacity(0.1),
                        border: Border.all(color: Colors.white24, width: 1),
                      ),
                      child: Icon(
                        Icons.network_check,
                        color: Colors.white,
                        size: 30,
                      ),
                    ),
                    const SizedBox(width: 16),
                    // App Title & Subtitle
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'Micro Panel',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white,
                              fontSize: 22,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'لوحة تحكم الشبكة الذكية',
                            style: TextStyle(
                              fontFamily: 'Tajawal',
                              color: Colors.white70,
                              fontSize: 14,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),

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

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

              // User Manager Section
              ExpansionTile(
                title: Row(
                  children: [
                    Icon(
                      Icons.manage_accounts,
                      color: Colors.white.withOpacity(0.7),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'إدارة اليوزر مانجر',
                      style: TextStyle(
                        fontFamily: 'Tajawal',
                        color: Colors.white.withOpacity(0.7),
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
                initiallyExpanded: true,
                children: [
                  _buildUniversalDrawerItem(
                    icon: Icons.people_outline,
                    title: 'قائمة المستخدمين',
                    onTap: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  UserManagerUserList(client: widget.client),
                          transitionsBuilder: (
                            context,
                            animation,
                            secondaryAnimation,
                            child,
                          ) {
                            const begin = Offset(0.0, 1.0);
                            const end = Offset.zero;
                            const curve = Curves.ease;
                            var tween = Tween(
                              begin: begin,
                              end: end,
                            ).chain(CurveTween(curve: curve));
                            return SlideTransition(
                              position: animation.drive(tween),
                              child: child,
                            );
                          },
                          transitionDuration: const Duration(milliseconds: 300),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.speed,
                    title: 'البروفايل',
                    onTap: () {
                      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),
                        ),
                      );
                    },
                  ),
                  _buildUniversalDrawerItem(
                    icon: Icons.bar_chart,
                    title: 'التقارير',
                    isActive: true,
                    onTap: () {},
                  ),
                ],
              ),

              // 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: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  FreeRebuildDB(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.backup,
                    title: 'النسخ الاحتياطي',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  backupSN(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.devices_other_outlined,
                    title: 'قطع البث',
                    onTap: () {
                      Navigator.push(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  Transmitters(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),
                        ),
                      );
                    },
                  ),
                ],
              ),

              // 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: () {
                      Navigator.pushReplacement(
                        context,
                        PageRouteBuilder(
                          pageBuilder:
                              (context, animation, secondaryAnimation) =>
                                  AboutApp(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),
                        ),
                      );
                    },
                  ),
                ],
              ),

              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,
    bool isActive = false,
  }) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 4, horizontal: 8),
      decoration: BoxDecoration(
        color: isActive ? _primaryColor.withOpacity(0.1) : Colors.transparent,
        borderRadius: BorderRadius.circular(8),
        border:
            isActive
                ? Border.all(color: _primaryColor.withOpacity(0.5), width: 1)
                : null,
      ),
      child: ListTile(
        leading: Icon(icon, color: isActive ? _primaryColor : color),
        title: Text(
          title,
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: isActive ? _primaryColor : color,
            fontSize: 14,
            fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
          ),
        ),
        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),
          ),
        ),
      ),
    );
  }

  Widget _buildMainContent({bool showHeader = true}) {
    final userCount = _filteredSessions.length;
    final totalPrice = _filteredSessions.fold(0, (sum, user) {
      final price = int.tryParse(user['price']?.toString() ?? '0') ?? 0;
      return sum + (price ~/ 100);
    });

    return Stack(
      children: [
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [
                _backgroundColor.withOpacity(0.9),
                _backgroundColor.withOpacity(0.7),
              ],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
          ),
          child: Column(
            children: [
              if (showHeader)
                Container(
                  height: 60,
                  padding: EdgeInsets.symmetric(horizontal: 8),
                  decoration: BoxDecoration(
                    color: Colors.white.withOpacity(0.05),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.menu, color: _textColor),
                        onPressed: () {},
                        padding: EdgeInsets.zero,
                      ),
                      Expanded(
                        child: Text(
                          'تقارير اليوزرمانجر',
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor,
                            fontSize: 20,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      if (userCount > 0)
                        Row(
                          children: [
                            Container(
                              padding: EdgeInsets.all(12),
                              decoration: BoxDecoration(
                                color: Colors.white.withOpacity(0.1),
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(color: Colors.white24),
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.people,
                                    color: Colors.white70,
                                    size: 20,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    'عدد المستخدمين: $userCount',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: Colors.white,
                                      fontSize: 15,
                                    ),
                                  ),
                                  SizedBox(width: 16),
                                  Icon(
                                    Icons.attach_money,
                                    color: Colors.greenAccent,
                                    size: 20,
                                  ),
                                  SizedBox(width: 6),
                                  Text(
                                    'الإجمالي: $totalPrice',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: Colors.greenAccent,
                                      fontSize: 15,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            SizedBox(width: 8),
                            IconButton(
                              icon: Icon(
                                Icons.picture_as_pdf,
                                color: _primaryColor,
                              ),
                              onPressed:
                                  _isLoadingNotifier.value
                                      ? null
                                      : () async {
                                        _loadingMessageNotifier.value =
                                            'جاري تحضير ملف التقرير ...';
                                        _isLoadingNotifier.value = true;
                                        try {
                                          await _generatePdf();
                                        } finally {
                                          _isLoadingNotifier.value = false;
                                          _loadingMessageNotifier.value = null;
                                        }
                                      },
                              tooltip: 'تصدير إلى PDF',
                            ),
                          ],
                        ),
                    ],
                  ),
                ),

              Padding(
                padding: const EdgeInsets.all(16.0),
                child: _buildDateRangeSelector(),
              ),

              Expanded(
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: _buildDataTable(),
                ),
              ),
            ],
          ),
        ),

        ValueListenableBuilder<bool>(
          valueListenable: _isLoadingNotifier,
          builder: (context, isLoading, child) {
            return isLoading
                ? Container(
                  color: Colors.black.withOpacity(0.5),
                  child: Center(
                    child: Container(
                      padding: EdgeInsets.all(20),
                      decoration: BoxDecoration(
                        color: _cardColor.withOpacity(0.9),
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircularProgressIndicator(color: _primaryColor),
                          SizedBox(height: 16),
                          ValueListenableBuilder<String?>(
                            valueListenable: _loadingMessageNotifier,
                            builder: (context, message, _) {
                              return Text(
                                message ?? '',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Tajawal',
                                  fontSize: 16,
                                ),
                              );
                            },
                          ),
                        ],
                      ),
                    ),
                  ),
                )
                : SizedBox.shrink();
          },
        ),
      ],
    );
  }
}

class MicroPanelSales {
  final RouterOSClient client;
  Socket? socket;

  MicroPanelSales({required this.client});

  String get host => client.address;
  int get port => client.port ?? 8728;
  String get user => client.user;
  String get pass => client.password;
  final _recvBuffer = <int>[];

  Future<void> connect() async {
    try {
      socket = await Socket.connect(host, port, timeout: Duration(seconds: 10));

      // الاستماع إلى البيانات الواردة
      socket!.listen(
        (data) {
          _recvBuffer.addAll(data);
        },
        onError: (error) {
          print('Socket error: $error');
          disconnect();
        },
        onDone: () {
          print('Socket connection closed by router');
          disconnect();
        },
      );

      // إرسال بيانات تسجيل الدخول
      await _sendLogin();
    } catch (e) {
      throw Exception('فشل الاتصال');
    }
  }

  Future<void> _sendLogin() async {
    if (socket == null) return;

    // إرسال اسم المستخدم
    await sendSentence(['/login', '=name=$user', '=password=$pass']);

    // قراءة الرد
    final response = await _readResponse();
    if (response.isEmpty || !response.any((s) => s.contains('!done'))) {
      throw Exception('فشل المصادقة');
    }
  }

  Future<void> sendSentence(List<String> words) async {
    if (socket == null) return;

    final buffer = _encodeSentence(words);
    socket!.add(buffer);
    await socket!.flush();
  }

  Future<List<List<String>>> sendSentenceWithResponse(
    List<String> words,
  ) async {
    if (socket == null) throw Exception('Socket is not connected');

    final buffer = _encodeSentence(words);
    socket!.add(buffer);
    await socket!.flush();

    return await _readSentences();
  }

  List<int> _encodeSentence(List<String> words) {
    final buffer = <int>[];
    for (final word in words) {
      final wordBytes = utf8.encode(word);
      final len = wordBytes.length;

      if (len < 0x80) {
        buffer.add(len);
      } else if (len < 0x4000) {
        buffer.add((len >> 8) | 0x80);
        buffer.add(len & 0xFF);
      } else if (len < 0x200000) {
        buffer.add((len >> 16) | 0xC0);
        buffer.add((len >> 8) & 0xFF);
        buffer.add(len & 0xFF);
      } else {
        buffer.add((len >> 24) | 0xE0);
        buffer.add((len >> 16) & 0xFF);
        buffer.add((len >> 8) & 0xFF);
        buffer.add(len & 0xFF);
      }

      buffer.addAll(wordBytes);
    }
    buffer.add(0); // نهاية الجملة
    return buffer;
  }

  Future<List<String>> _readResponse() async {
    if (socket == null) return [];

    final sentences = await _readSentences();
    return sentences.expand((s) => s).toList();
  }

  void disconnect() {
    socket?.close();
    socket = null;
  }

  Future<List<List<String>>> _readSentences() async {
    final sentences = <List<String>>[];
    while (true) {
      await Future.delayed(Duration(milliseconds: 100));

      if (_recvBuffer.isEmpty) continue;

      final buf = List<int>.from(_recvBuffer);
      try {
        var i = 0;
        while (i < buf.length) {
          final sentence = <String>[];
          while (i < buf.length && buf[i] != 0) {
            int len = buf[i++];
            int bytesCount = 1;

            if (len & 0x80 != 0) {
              bytesCount =
                  (len & 0xC0) == 0x80
                      ? 2
                      : (len & 0xE0) == 0xC0
                      ? 3
                      : 4;
              len = ((len & 0x7F) << ((bytesCount - 1) * 8));

              for (int j = 0; j < bytesCount - 1 && i < buf.length; j++) {
                len |= buf[i++] << ((bytesCount - 2 - j) * 8);
              }
            }

            if (i + len > buf.length) {
              i -= bytesCount;
              break;
            }

            sentence.add(utf8.decode(buf.sublist(i, i + len)));
            i += len;
          }

          if (i < buf.length && buf[i] == 0) {
            i++; // تخطي حرف الإنهاء
            sentences.add(sentence);

            // إذا كانت الجملة تحتوي على !done، نخرج
            if (sentence.isNotEmpty && sentence.first == '!done') {
              _recvBuffer.removeRange(0, i);
              return sentences;
            }
          } else {
            break; // بيانات غير مكتملة
          }
        }

        _recvBuffer.removeRange(0, i);

        // إذا وجدنا جملة !done نعود بالنتيجة
        if (sentences.any((s) => s.isNotEmpty && s.first == '!done')) {
          return sentences;
        }
      } catch (e) {
        print('Error parsing sentences');
        break;
      }
    }
    return sentences;
  }
}