اريد حل هذة المشكلة
Launching lib\main.dart on Windows in debug mode...
Nuget.exe not found, trying to download or use cached version.
√ Built build\windows\x64\runner\Debug\micro_panel.exe
Connecting to VM Service at ws://127.0.0.1:14235/sPFNFTrKCus=/ws
Connected to the VM Service.
flutter: تم حفظ إصدار الراوتر بنجاح في: C:\Users\PC\Documents/router_version.json
flutter: All timers stopped
flutter: Client saved to AppSession
flutter: Active Users Count: 1
flutter: first_fetch
flutter: All timers stopped
flutter: All timers stopped

════════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building LayoutBuilder:
Null check operator used on a null value

The relevant error-causing widget was:
    LayoutBuilder LayoutBuilder:file:///E:/MicroPanel_flutter/micro_panel/lib/AddHotspotUser.dart:702:14

When the exception was thrown, this was the stack:
#0      _AddHotspotCardsPageState._buildMultipleCardsTab (package:micro_panel/AddHotspotUser.dart:1405:63)
#1      _AddHotspotCardsPageState._buildDesktopLayout (package:micro_panel/AddHotspotUser.dart:799:29)
#2      _AddHotspotCardsPageState.build.<anonymous closure> (package:micro_panel/AddHotspotUser.dart:705:20)
#3      _LayoutBuilderElement._rebuildWithConstraints.updateChildCallback (package:flutter/src/widgets/layout_builder.dart:201:77)
#4      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3056:19)
#5      _LayoutBuilderElement._rebuildWithConstraints (package:flutter/src/widgets/layout_builder.dart:240:12)
#6      RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:2827:17)
#7      PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:1161:15)
#8      RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:2826:14)
#9      RenderConstrainedLayoutBuilder.rebuildIfNecessary (package:flutter/src/widgets/layout_builder.dart:293:5)
#10     _RenderLayoutBuilder.performLayout (package:flutter/src/widgets/layout_builder.dart:390:5)
#11     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#12     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#13     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#14     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#15     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#16     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#17     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#18     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#19     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#20     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#21     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#22     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#23     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#24     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#25     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#26     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#27     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#28     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#29     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#30     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3748:14)
#31     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#32     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#33     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#34     _RenderTheaterMixin.layoutChild (package:flutter/src/widgets/overlay.dart:1076:13)
#35     _RenderTheater.performLayout (package:flutter/src/widgets/overlay.dart:1422:9)
#36     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:2548:7)
#37     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:1112:18)
#38     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:1125:15)
#39     RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:616:23)
#40     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1231:13)
#41     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:482:5)
#42     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1442:15)
#43     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1355:9)
#44     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1208:5)
#45     _invoke (dart:ui/hooks.dart:316:13)
#46     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:428:5)
#47     _drawFrame (dart:ui/hooks.dart:288:31)

════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by widgets library ═══════════════════════════════════
Null check operator used on a null value
The relevant error-causing widget was:
    LayoutBuilder LayoutBuilder:file:///E:/MicroPanel_flutter/micro_panel/lib/AddHotspotUser.dart:702:14
════════════════════════════════════════════════════════════════════════════════
flutter: first_fetch

════════ Exception caught by widgets library ═══════════════════════════════════
The following _TypeError was thrown building LayoutBuilder:
Null check operator used on a null value

The relevant error-causing widget was:
    LayoutBuilder LayoutBuilder:file:///E:/MicroPanel_flutter/micro_panel/lib/AddHotspotUser.dart:702:14

When the exception was thrown, this was the stack:
#0      _AddHotspotCardsPageState._buildMultipleCardsTab (package:micro_panel/AddHotspotUser.dart:1402:63)
#1      _AddHotspotCardsPageState._buildDesktopLayout (package:micro_panel/AddHotspotUser.dart:799:29)
#2      _AddHotspotCardsPageState.build.<anonymous closure> (package:micro_panel/AddHotspotUser.dart:705:20)
#3      _LayoutBuilderElement._rebuildWithConstraints.updateChildCallback (package:flutter/src/widgets/layout_builder.dart:201:77)
#4      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:3056:19)
#5      _LayoutBuilderElement._rebuildWithConstraints (package:flutter/src/widgets/layout_builder.dart:240:12)
#6      RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:2827:17)
#7      PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:1161:15)
#8      RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:2826:14)
#9      RenderConstrainedLayoutBuilder.rebuildIfNecessary (package:flutter/src/widgets/layout_builder.dart:293:5)
#10     _RenderLayoutBuilder.performLayout (package:flutter/src/widgets/layout_builder.dart:390:5)
#11     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#12     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#13     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#14     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#15     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#16     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#17     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#18     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#19     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#20     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#21     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#22     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#23     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#24     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#25     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#26     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#27     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#28     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#29     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#30     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#31     RenderOffstage.performLayout (package:flutter/src/rendering/proxy_box.dart:3750:13)
#32     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#33     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#34     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#35     _RenderTheaterMixin.layoutChild (package:flutter/src/widgets/overlay.dart:1076:13)
#36     _RenderTheater.performLayout (package:flutter/src/widgets/overlay.dart:1422:9)
#37     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#38     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#39     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#40     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#41     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#42     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#43     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#44     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#45     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#46     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#47     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#48     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#49     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#50     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#51     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#52     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#53     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#54     RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:115:18)
#55     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#56     RenderPadding.performLayout (package:flutter/src/rendering/shifted_box.dart:243:12)
#57     RenderObject.layout (package:flutter/src/rendering/object.dart:2715:7)
#58     RenderView.performLayout (package:flutter/src/rendering/view.dart:294:12)
#59     RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:2548:7)
#60     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:1112:18)
#61     PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:1125:15)
#62     RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:616:23)
#63     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:1231:13)
#64     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:482:5)
#65     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1442:15)
#66     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1355:9)
#67     SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:1064:9)
#68     PlatformDispatcher.scheduleWarmUpFrame.<anonymous closure> (dart:ui/platform_dispatcher.dart:873:16)
#72     _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:194:12)
(elided 3 frames from class _Timer and dart:async-patch)

════════════════════════════════════════════════════════════════════════════════
Reloaded 1 of 2052 libraries in 1,381ms (compile: 110 ms, reload: 525 ms, reassemble: 484 ms).

للعلم هذة المشكلة تظهر فقط عن تشغيل البرنامج على الحاسوب
الكود
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:micro_panel/AboutApp.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/UserManagerProfile.dart';
import 'package:micro_panel/UserManagerReport.dart';
import 'package:micro_panel/UserManagerUserList.dart';
import 'package:micro_panel/hotspotUserList.dart';
import 'package:open_file/open_file.dart';
import 'package:router_os_client/router_os_client.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';

class AddHotspotCardsPage extends StatefulWidget {
  final RouterOSClient client;
  final int initialTab;
  const AddHotspotCardsPage({
    super.key,
    required this.client,
    this.initialTab = 0,
  });

  @override
  State<AddHotspotCardsPage> createState() => _AddHotspotCardsPageState();
}

class _AddHotspotCardsPageState extends State<AddHotspotCardsPage>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final _singleUserFormKey = GlobalKey<FormState>();
  final _multiUserFormKey = GlobalKey<FormState>();
  int _numberOfCards = 45;
  int _digitsCount = 7;
  double _usernameFontSize = 12.0;
  double _passwordFontSize = 12.0;
  String _profile = 'default';
  List<String> _availableProfiles = [];
  String _usernamePrefix = '';
  String _username = '';
  String _password = '';
  int _validityDays = 30;
  int _limitBytes = 250;
  int _limitHours = 0;
  bool _isLoading = false;
  double _progress = 0.0;
  String _progressMessage = '';
  File? _backgroundImage;
  Offset _usernamePosition = Offset(0.3, 0.7);
  Offset _passwordPosition = Offset(0.3, 0.8);
  bool _isDraggingUsername = false;
  bool _isDraggingPassword = false;
  Uint8List? _imageBytes;
  String _generationType = 'username_only';
  final List<Map<String, String>> _generatedCards = [];
  bool _showCounter = false;
  String _dataUnit = 'MB';
  int _successfulCards = 0;
  int _failedCards = 0;
  int _rowsPerPage = 15;
  int _columnsPerPage = 3;
  int _usernameDigitsCount = 7;
  int _passwordDigitsCount = 8;
  double _actualImageWidth = 0.0;
  double _actualImageHeight = 0.0;
  double _previewCardWidth = 400;
  double _previewCardHeight = 250;
  Color _primaryColor = const Color(0xFF3B82F6);
  Color _backgroundColor = const Color(0xFF0A192F);
  Color _cardColor = const Color(0xFF172A46);
  Color _textColor = Colors.white;
  bool _includeSerialNumber = false;
  Offset _serialNumberPosition = Offset(0.1, 0.1);
  double _serialNumberFontSize = 6.0;
  String _serialNumberPrefix = '';
  int _currentSerialNumber = 0;
  int _firstSerialNumber = 0;
  String? _selectedElement;

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

  int _calculateLimitBytes(int value, String unit) {
    switch (unit) {
      case 'MB':
        return value * 1024 * 1024;
      case 'GB':
        return value * 1024 * 1024 * 1024;
      default:
        return value;
    }
  }

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: widget.initialTab,
    );
    Future.delayed(Duration(milliseconds: 150), () {
      _fetchHotspotProfiles();
    });
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _fetchHotspotProfiles() async {
    setState(() {
      _isLoading = true;
      _progressMessage = 'جلب قائمة البروفايلات...';
    });
    try {
      final response = await widget.client.talk([
        '/ip/hotspot/user/profile/print',
      ]);
      final profiles =
          response
              .where((item) => item.containsKey('name'))
              .map((item) => item['name'] as String)
              .toList();
      if (profiles.isNotEmpty) {
        setState(() {
          _availableProfiles = profiles;
          _profile = profiles.first;
        });
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'خطأ في جلب البروفايلات',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }

  Future<void> _generateHotspotCards() async {
    // اجعل شرط الصورة مطلوب فقط في تبويب "مجموعة مستخدمين"
    if (_tabController.index == 1 && _backgroundImage == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'الرجاء اختيار صورة خلفية أولاً',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    final formKey =
        _tabController.index == 0 ? _singleUserFormKey : _multiUserFormKey;
    if (!formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'الرجاء ملء جميع الحقول المطلوبة',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    // جلب الرقم التسلسلي الأول من أول مستخدم يتم إنشاؤه
    if (_includeSerialNumber) {
      setState(() {
        _isLoading = true;
        _progressMessage = 'جلب الرقم التسلسلي الأول...';
      });

      try {
        // إنشاء أول مستخدم مؤقت للحصول على الرقم التسلسلي
        final tempUsername = 'temp_${DateTime.now().millisecondsSinceEpoch}';
        await widget.client.talk([
          '/ip/hotspot/user/add',
          '=name=$tempUsername',
          '=password=temp123',
          '=profile=$_profile',
        ]);

        // جلب الرقم التسلسلي للمستخدم المؤقت
        final response = await widget.client.talk([
          '/ip/hotspot/user/print',
          '?name=$tempUsername',
          '=.proplist=.id',
        ]);

        if (response.isNotEmpty) {
          final id = response.first['.id'] as String;
          final parts = id.split('*');
          if (parts.length > 1) {
            final hexPart = parts[1];
            // تحويل من Hex إلى int باستخدام radix=16
            setState(() {
              _firstSerialNumber = int.tryParse(hexPart, radix: 16) ?? 0;
            });
          }
        }
        // حذف المستخدم المؤقت
        await widget.client.talk([
          '/ip/hotspot/user/remove',
          '=.id=$tempUsername',
        ]);
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'خطأ في جلب الرقم التسلسلي',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
              backgroundColor: Colors.red,
            ),
          );
        }
      } finally {
        setState(() {
          _isLoading = false;
        });
      }
    }
    int calculatedLimitBytes =
        _limitBytes > 0 ? _calculateLimitBytes(_limitBytes, _dataUnit) : 0;
    setState(() {
      _isLoading = true;
      _progress = 0.0;
      _progressMessage = 'بدء إنشاء الكروت...';
      _generatedCards.clear();
      _showCounter = true;
      _successfulCards = 0;
      _failedCards = 0;
      _currentSerialNumber = 0; // إعادة تعيين العداد عند بدء عملية جديدة
    });

    final uniqueUsernames = <String>{};

    for (int i = 0; i < _numberOfCards; i++) {
      late String username;
      late String password;

      // الدوال الجديدة المستقلة
      String _generateUsernameOnly(int index, Set<String> uniqueUsernames) {
        final random = Random();
        String generatedUsername;
        do {
          final number = random.nextInt(pow(10, _usernameDigitsCount).toInt());
          generatedUsername =
              '$_usernamePrefix${number.toString().padLeft(_usernameDigitsCount, '0')}';
        } while (uniqueUsernames.contains(generatedUsername));

        uniqueUsernames.add(generatedUsername);
        return generatedUsername;
      }

      Map<String, String> _generateSimilarCredentials(
        int index,
        Set<String> uniqueUsernames,
      ) {
        final random = Random();
        String generatedUsername;
        do {
          final number = random.nextInt(pow(10, _usernameDigitsCount).toInt());
          generatedUsername =
              '$_usernamePrefix${number.toString().padLeft(_usernameDigitsCount, '0')}';
        } while (uniqueUsernames.contains(generatedUsername));

        uniqueUsernames.add(generatedUsername);
        return {'username': generatedUsername, 'password': generatedUsername};
      }

      Map<String, String> _generateUniqueCredentials(
        int index,
        Set<String> uniqueUsernames,
      ) {
        final random = Random.secure();
        String username;
        String password;

        do {
          final number = random.nextInt(pow(10, _usernameDigitsCount).toInt());
          username =
              '${_usernamePrefix}${number.toString().padLeft(_usernameDigitsCount, '0')}';
          password = _generateRandomPassword();
        } while (uniqueUsernames.contains(username));

        uniqueUsernames.add(username);
        return {'username': username, 'password': password};
      }

      // الكود المعدل في دالة _generateHotspotCards()
      if (_tabController.index == 0) {
        // حالة المستخدم الواحد
        username = _username;
        password = _password;
      } else {
        // حالة مجموعة المستخدمين
        switch (_generationType) {
          case 'username_only':
            username = _generateUsernameOnly(i, uniqueUsernames);
            password = '';
            break;
          case 'similar_username':
            final credentials = _generateSimilarCredentials(i, uniqueUsernames);
            username = credentials['username']!;
            password = credentials['password']!;

            break;
          case 'unique_credentials':
            final credentials = _generateUniqueCredentials(i, uniqueUsernames);
            username = credentials['username']!;
            password = credentials['password']!;
            break;
          default:
            username = '${_usernamePrefix}${i + 1}';
            password = _generateRandomPassword();
        }
      }

      try {
        final now = DateTime.now();
        final expiryDate = now.add(Duration(days: _validityDays));
        final formattedNow =
            '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
        final expiryDateStr =
            '${expiryDate.year}-${expiryDate.month.toString().padLeft(2, '0')}-${expiryDate.day.toString().padLeft(2, '0')}';

        final totalMinutes = (_validityDays * 24 * 60) + (_limitHours * 60);

        await widget.client.talk([
          '/ip/hotspot/user/add',
          '=name=$username',
          if (password.isNotEmpty) '=password=$password',
          '=profile=$_profile',
          if (_validityDays > 0 || _limitHours > 0)
            '=comment=Added on $formattedNow, Valid until $expiryDateStr',
          if (calculatedLimitBytes > 0)
            '=limit-bytes-total=$calculatedLimitBytes',
          if (_validityDays > 0 || _limitHours > 0)
            '=limit-uptime=${totalMinutes}m',
        ]);

        setState(() {
          _successfulCards++;
        });
        _generatedCards.add({'username': username, 'password': password});
      } catch (e) {
        setState(() {
          _failedCards++;
        });
      }

      setState(() {
        _progress = (i + 1) / _numberOfCards;
        _progressMessage = 'جاري إضافة الكروت... ${i + 1}/$_numberOfCards';
      });
    }

    await Future.delayed(const Duration(milliseconds: 500));
    setState(() {
      _showCounter = false;
    });

    if (mounted) {
      final message =
          _successfulCards > 0
              ? 'تم إنشاء $_successfulCards كرت بنجاح${_failedCards > 0 ? ' (فشل $_failedCards)' : ''}'
              : 'فشل في إنشاء جميع الكروت';
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message, style: TextStyle(fontFamily: 'Tajawal')),
          backgroundColor: _successfulCards > 0 ? Colors.green : Colors.red,
          duration: const Duration(seconds: 5),
        ),
      );
    }

    setState(() {
      _isLoading = false;
      _progress = 0.0;
    });
    await _generateAndSavePdf();
  }

  String _generateRandomPassword() {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    final random = Random.secure(); // استخدام Random.secure() بدلاً من Random()
    return String.fromCharCodes(
      Iterable.generate(
        _passwordDigitsCount,
        (_) => chars.codeUnitAt(random.nextInt(chars.length)),
      ),
    );
  }

  Future<void> _pickBackgroundImage() async {
    final result = await FilePicker.platform.pickFiles(
      type: FileType.image,
      allowMultiple: false,
    );
    if (result != null && result.files.isNotEmpty) {
      final file = File(result.files.single.path!);
      final bytes = await file.readAsBytes();

      final image = FileImage(file);
      final completer = Completer<ImageInfo>();
      image
          .resolve(ImageConfiguration())
          .addListener(
            ImageStreamListener((info, _) {
              if (!completer.isCompleted) {
                completer.complete(info);
              }
            }),
          );

      final imageInfo = await completer.future;
      final imageWidth = imageInfo.image.width.toDouble();
      final imageHeight = imageInfo.image.height.toDouble();

      setState(() {
        _backgroundImage = file;
        _imageBytes = bytes;
        _actualImageWidth = imageWidth;
        _actualImageHeight = imageHeight;
        // ضبط المواضع الافتراضية في المنتصف
        _usernamePosition = Offset(0.5, 0.4);
        _passwordPosition = Offset(0.5, 0.6);
      });
    }
  }

  Future<void> _generateAndSavePdf() async {
    if (_imageBytes == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'الرجاء اختيار صورة خلفية أولاً',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
      _progressMessage = 'جاري إنشاء ملف PDF...';
    });

    try {
      final pdf = pw.Document(compress: true);
      final image = pw.MemoryImage(_imageBytes!);
      const pageFormat = PdfPageFormat.a4;
      const horizontalMargin = 5.0;
      const verticalMargin = 5.0;
      const spacingBetweenCards = 3.0;
      const spacingBetweenRows = 3.0;
      const offsetX = 3.0; // تحريك لليمين
      const offsetY = -5.0; // تحريك للأعلى

      final availableWidth = pageFormat.width - (horizontalMargin * 2);
      final availableHeight = pageFormat.height - (verticalMargin * 2);

      final cardWidth =
          (availableWidth - ((_columnsPerPage - 1) * spacingBetweenCards)) /
          _columnsPerPage;
      final cardHeight =
          (availableHeight - ((_rowsPerPage - 1) * spacingBetweenRows)) /
          _rowsPerPage;

      final cardsPerPage = _rowsPerPage * _columnsPerPage;
      final totalPages = (_generatedCards.length / cardsPerPage).ceil();

      for (int pageNum = 0; pageNum < totalPages; pageNum++) {
        final startIndex = pageNum * cardsPerPage;
        final endIndex = min(startIndex + cardsPerPage, _generatedCards.length);
        final rows = <pw.Widget>[];

        for (int row = 0; row < _rowsPerPage; row++) {
          final cardIndex = startIndex + (row * _columnsPerPage);
          if (cardIndex >= endIndex) break;
          final rowCards = <pw.Widget>[];

          for (int col = 0; col < _columnsPerPage; col++) {
            final index = cardIndex + col;
            if (index >= endIndex) break;
            final card = _generatedCards[index];

            // المواقع المحسوبة باستخدام نسب المعاينة
            final usernameX = _usernamePosition.dx * cardWidth;
            final usernameY = _usernamePosition.dy * cardHeight;
            final passwordX = _passwordPosition.dx * cardWidth;
            final passwordY = _passwordPosition.dy * cardHeight;

            final adjustedOffsetX = offsetX;
            final adjustedOffsetY = offsetY;

            rowCards.add(
              pw.Container(
                width: cardWidth,
                height: cardHeight,
                margin: pw.EdgeInsets.only(
                  right: col < _columnsPerPage - 1 ? spacingBetweenCards : 0,
                  bottom: row < _rowsPerPage - 1 ? spacingBetweenRows : 0,
                ),
                decoration: pw.BoxDecoration(
                  border: pw.Border.all(color: PdfColors.black, width: 0.5),
                  image: pw.DecorationImage(image: image, fit: pw.BoxFit.fill),
                ),
                child: pw.Stack(
                  children: [
                    if (_includeSerialNumber)
                      pw.Positioned(
                        left:
                            _serialNumberPosition.dx * cardWidth +
                            adjustedOffsetX,
                        top:
                            _serialNumberPosition.dy * cardHeight +
                            adjustedOffsetY +
                            17,
                        child: pw.Text(
                          _getNextSerialNumber(),
                          style: pw.TextStyle(
                            color: PdfColors.black,
                            fontSize: _serialNumberFontSize,
                            fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                      ),
                    pw.Positioned(
                      left: _usernamePosition.dx * cardWidth + adjustedOffsetX,
                      top: _usernamePosition.dy * cardHeight + adjustedOffsetY,
                      child: pw.Text(
                        card['username']!,
                        style: pw.TextStyle(
                          color: PdfColors.black,
                          fontSize: _usernameFontSize,
                          fontWeight: pw.FontWeight.bold,
                        ),
                      ),
                    ),
                    if (card['password']!.isNotEmpty)
                      pw.Positioned(
                        left:
                            _passwordPosition.dx * cardWidth + adjustedOffsetX,
                        top:
                            _passwordPosition.dy * cardHeight +
                            adjustedOffsetY +
                            16,
                        child: pw.Text(
                          card['password']!,
                          style: pw.TextStyle(
                            color: PdfColors.black,
                            fontSize: _passwordFontSize,
                            fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                      ),
                  ],
                ),
              ),
            );
          }

          rows.add(pw.Row(children: rowCards));
        }

        pdf.addPage(
          pw.Page(
            margin: pw.EdgeInsets.symmetric(
              horizontal: horizontalMargin,
              vertical: verticalMargin,
            ),
            pageFormat: pageFormat,
            build:
                (pw.Context context) => pw.Column(
                  children: rows,
                  mainAxisAlignment: pw.MainAxisAlignment.start,
                ),
          ),
        );
      }

      // اختيار مسار الحفظ يدوياً
      final result = await FilePicker.platform.getDirectoryPath();
      if (result == null) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text(
                'لم يتم اختيار مسار للحفظ',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
          );
        }
        return;
      }

      // إنشاء اسم الملف مع التاريخ والوقت
      final now = DateTime.now();
      final formattedTime =
          '${now.year}-${now.month.toString().padLeft(2, "0")}-${now.day.toString().padLeft(2, "0")}_${now.hour.toString().padLeft(2, "0")}-${now.minute.toString().padLeft(2, "0")}-${now.second.toString().padLeft(2, "0")}';
      final fileName = 'كروت_الهوتسبوت_$formattedTime.pdf';
      final filePath = '$result/$fileName';

      // حفظ الملف
      final file = File(filePath);
      final pdfBytes = await pdf.save();
      await file.writeAsBytes(pdfBytes.toList());
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'تم حفظ ملف PDF بنجاح في: $filePath',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.green,
          ),
        );
        OpenFile.open(filePath);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'خطأ في حفظ ملف PDF',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.red,
          ),
        );
        debugPrint('Error:  ');
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<String?> _pickSavePath() async {
    final result = await FilePicker.platform.getDirectoryPath();
    if (result == null) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text(
              'لم يتم اختيار مسار للحفظ',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
          ),
        );
      }
      return null;
    }

    final now = DateTime.now();
    final formattedTime =
        '${now.year}-${now.month.toString().padLeft(2, "0")}-${now.day.toString().padLeft(2, "0")}_${now.hour.toString().padLeft(2, "0")}-${now.minute.toString().padLeft(2, "0")}-${now.second.toString().padLeft(2, "0")}';
    final fileName = 'كروت_الهوتسبوت_$formattedTime.pdf';
    return '$result/$fileName';
  }

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

  Widget _buildDesktopLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      body: Row(
        children: [
          // الشريط الجانبي
          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: 40),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 16),
                    child: Row(
                      children: [
                        Icon(Icons.credit_card, color: _primaryColor, size: 28),
                        const SizedBox(width: 10),
                        Text(
                          'إنشاء كروت هوتسبوت',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            fontFamily: 'Tajawal',
                          ),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 30),
                  Expanded(child: _buildDesktopNavigation()),
                ],
              ),
            ),
          ),

          // المحتوى الرئيسي
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    _backgroundColor.withOpacity(0.9),
                    _backgroundColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: Column(
                children: [
                  Container(
                    height: 60,
                    color: Colors.white.withOpacity(0.05),
                    child: TabBar(
                      controller: _tabController,
                      indicatorColor: _primaryColor,
                      indicatorWeight: 3,
                      labelColor: _primaryColor,
                      unselectedLabelColor: Colors.white.withOpacity(0.5),
                      tabs: const [
                        Tab(icon: Icon(Icons.person_add), text: 'مستخدم واحد'),
                        Tab(
                          icon: Icon(Icons.group_add),
                          text: 'مجموعة مستخدمين',
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Stack(
                      children: [
                        TabBarView(
                          controller: _tabController,
                          children: [
                            _buildSingleCardTab(),
                            _buildMultipleCardsTab(),
                          ],
                        ),
                        if (_isLoading) _buildLoadingOverlay(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopNavigation() {
    return Container(
      height: MediaQuery.of(context).size.height,
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // قسم الإدارة الرئيسية
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Text(
                'الإدارة الرئيسية',
                style: TextStyle(
                  color: Colors.white.withOpacity(0.5),
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                  fontFamily: 'Tajawal',
                ),
              ),
            ),
            _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,
                            ),
                      ),
                    );
                  },
                ),
              ],
            ),

            // قسم اليوزر مانجر (قابل للطي)
            // في _buildDesktopNavigation()
            _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:
                            (context) =>
                                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:
                            (context) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 0,
                            ),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.credit_score,
                  title: 'اضافة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 1,
                            ),
                      ),
                    );
                  },
                ),

                _buildNavItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) =>
                                UserManagerSession(client: widget.client),
                      ),
                    );
                  },
                ),
              ],
            ),

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

            // قسم المساعدة والدعم (قابل للطي)
            _buildExpandableSection(
              title: 'المساعدة والدعم',
              icon: Icons.help,
              initiallyExpanded: isHelpExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isHelpExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.help_outline,
                  title: 'المركز المساعدة',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => HelpDesk(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(
                        builder: (_) => SendNotes(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  isActive: false,
                  onTap: () {
                    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 _buildMobileLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      appBar: AppBar(
        title: Text(
          'إنشاء كروت هوتسبوت',
          style: TextStyle(
            color: _textColor,
            fontSize: 20,
            fontFamily: 'Tajawal',
          ),
        ),
        centerTitle: true,
        backgroundColor: _backgroundColor,
        elevation: 0,
        iconTheme: IconThemeData(color: _textColor),
        bottom: TabBar(
          controller: _tabController,
          indicatorColor: _primaryColor,
          indicatorWeight: 3,
          labelColor: _primaryColor,
          unselectedLabelColor: Colors.white.withOpacity(0.5),
          tabs: const [
            Tab(icon: Icon(Icons.person_add), text: 'مستخدم واحد'),
            Tab(icon: Icon(Icons.group_add), text: 'مجموعة مستخدمين'),
          ],
        ),
      ),
      drawer: _buildUniversalDrawer(),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  _backgroundColor.withOpacity(0.9),
                  _backgroundColor.withOpacity(0.7),
                ],
              ),
            ),
            child: TabBarView(
              controller: _tabController,
              children: [_buildSingleCardTab(), _buildMultipleCardsTab()],
            ),
          ),
          if (_isLoading) _buildLoadingOverlay(),
        ],
      ),
    );
  }

  Widget _buildSingleCardTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _singleUserFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSettingsCard('إعدادات الكرت', _buildSingleFormFields()),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed:
                  _isLoading
                      ? null
                      : () {
                        _numberOfCards = 1;
                        _generateHotspotCards();
                      },
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
                elevation: 3,
                shadowColor: _primaryColor.withOpacity(0.3),
              ),
              child: const Text(
                'إنشاء الكرت',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildMultipleCardsTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _multiUserFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSettingsCard(
              'إعدادات مجموعة الكروت',
              Column(
                children: [
                  _buildCommonFormFields(),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _rowsPerPage,
                          items:
                              List.generate(20, (index) => index + 1)
                                  .map(
                                    (value) => DropdownMenuItem<int>(
                                      value: value,
                                      child: Text(
                                        '$value صفوف',
                                        style: TextStyle(
                                          color: _textColor,
                                          fontFamily: 'Tajawal',
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged:
                              (value) => setState(() => _rowsPerPage = value!),
                          decoration: _buildInputDecoration(
                            'عدد الصفوف في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                          style: TextStyle(color: _textColor),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _columnsPerPage,
                          items:
                              [3, 4]
                                  .map(
                                    (value) => DropdownMenuItem<int>(
                                      value: value,
                                      child: Text(
                                        '$value أعمدة',
                                        style: TextStyle(
                                          color: _textColor,
                                          fontFamily: 'Tajawal',
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged:
                              (value) =>
                                  setState(() => _columnsPerPage = value!),
                          decoration: _buildInputDecoration(
                            'عدد الأعمدة في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                          style: TextStyle(color: _textColor),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            CheckboxListTile(
              title: Text(
                'إضافة الرقم التسلسلي',
                style: TextStyle(color: _textColor, fontFamily: 'Tajawal'),
              ),
              value: _includeSerialNumber,
              onChanged: (value) {
                setState(() {
                  _includeSerialNumber = value!;
                });
              },
              activeColor: _primaryColor,
            ),

            ElevatedButton(
              onPressed:
                  _isLoading ||
                          (_tabController.index == 0 &&
                              !_singleUserFormKey.currentState!.validate()) ||
                          (_tabController.index == 1 &&
                              !_multiUserFormKey.currentState!.validate()) ||
                          _backgroundImage == null
                      ? null
                      : _generateHotspotCards,
              style: ElevatedButton.styleFrom(
                backgroundColor:
                    _isLoading ||
                            (_tabController.index == 0 &&
                                !_singleUserFormKey.currentState!.validate()) ||
                            (_tabController.index == 1 &&
                                !_multiUserFormKey.currentState!.validate()) ||
                            _backgroundImage == null
                        ? _primaryColor.withOpacity(0.5)
                        : _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
                elevation: 3,
                shadowColor: _primaryColor.withOpacity(0.3),
              ),
              child: const Text(
                'إنشاء الكروت',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
            const SizedBox(height: 24),
            _buildDesignCard(context),
          ],
        ),
      ),
    );
  }

  InputDecoration _buildInputDecoration(String labelText, {String? hintText}) {
    return InputDecoration(
      labelText: labelText,
      hintText: hintText ?? '',
      labelStyle: TextStyle(color: _textColor.withOpacity(0.8)),
      hintStyle: TextStyle(color: _textColor.withOpacity(0.5)),
      border: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: _textColor.withOpacity(0.2)),
      ),
      enabledBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: _textColor.withOpacity(0.2)),
      ),
      focusedBorder: OutlineInputBorder(
        borderRadius: BorderRadius.circular(8),
        borderSide: BorderSide(color: _primaryColor),
      ),
      filled: true,
      fillColor: _textColor.withOpacity(0.05),
    );
  }

  Widget _buildSingleFormFields() {
    return Column(
      children: [
        TextFormField(
          initialValue: _username,
          decoration: _buildInputDecoration('اسم المستخدم'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty) return 'يجب إدخال اسم المستخدم';
            return null;
          },
          onChanged: (value) => setState(() => _username = value),
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _password,
          obscureText: true,
          decoration: _buildInputDecoration('كلمة المرور'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (_tabController.index == 0) {
              return null;
            } else {
              if (value == null || value.isEmpty)
                return 'يجب إدخال كلمة المرور';
            }
            return null;
          },
          onChanged: (value) => setState(() => _password = value),
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _profile,
          items:
              _availableProfiles
                  .map(
                    (profile) => DropdownMenuItem(
                      value: profile,
                      child: Text(
                        profile,
                        style: TextStyle(
                          color: _textColor,
                          fontFamily: 'Tajawal',
                        ),
                      ),
                    ),
                  )
                  .toList(),
          onChanged: (value) => setState(() => _profile = value!),
          decoration: _buildInputDecoration('بروفايل الهوتسبوت'),
          dropdownColor: _cardColor,
          style: TextStyle(color: _textColor),
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _validityDays.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration('مدة الصلاحية (أيام)'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty || int.tryParse(value) == null)
              return 'يجب إدخال عدد صحيح';
            return null;
          },
          onChanged:
              (value) =>
                  setState(() => _validityDays = int.tryParse(value) ?? 30),
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: TextFormField(
                initialValue: _limitBytes.toString(),
                keyboardType: TextInputType.number,
                decoration: _buildInputDecoration(
                  'الكمية',
                  hintText: 'مثال: 20',
                ),
                style: TextStyle(color: _textColor),
                onChanged:
                    (value) =>
                        setState(() => _limitBytes = int.tryParse(value) ?? 0),
              ),
            ),
            const SizedBox(width: 8),
            DropdownButton<String>(
              value: _dataUnit,
              items: const [
                DropdownMenuItem(
                  value: 'MB',
                  child: Text(
                    'ميغابايت',
                    style: TextStyle(fontFamily: 'Tajawal'),
                  ),
                ),
                DropdownMenuItem(
                  value: 'GB',
                  child: Text(
                    'جيجابايت',
                    style: TextStyle(fontFamily: 'Tajawal'),
                  ),
                ),
              ],
              onChanged: (value) => setState(() => _dataUnit = value!),
              dropdownColor: _cardColor,
              style: TextStyle(color: _textColor),
            ),
          ],
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _limitHours.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration('عدد الساعات'),
          style: TextStyle(color: _textColor),
          onChanged:
              (value) => setState(() => _limitHours = int.tryParse(value) ?? 0),
        ),
      ],
    );
  }

  Widget _buildCommonFormFields() {
    return Column(
      children: [
        TextFormField(
          initialValue: _numberOfCards.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration(
            'عدد الكروت المراد إنشاؤها (الحد الأقصى 1500)',
          ),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty || int.tryParse(value) == null) {
              return 'يجب إدخال عدد صحيح';
            }
            final num = int.parse(value);
            if (num <= 0) {
              return 'يجب إدخال عدد صحيح موجب';
            }
            if (num > 1500) {
              return 'الحد الأقصى لعدد المستخدمين في الدفعة الواحدة هو 1500';
            }
            return null;
          },
          onChanged: (value) {
            final num = int.tryParse(value) ?? 1;
            if (num > 1500) {
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text(
                    'الحد الأقصى لعدد المستخدمين في الدفعة الواحدة هو 1500',
                    style: TextStyle(fontFamily: 'Tajawal'),
                  ),
                  backgroundColor: Colors.red,
                ),
              );
              setState(() => _numberOfCards = 1500);
            } else {
              setState(() => _numberOfCards = num);
            }
          },
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _generationType,
          items: const [
            DropdownMenuItem(
              value: 'username_only',
              child: Text(
                'اسم مستخدم فقط',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
            DropdownMenuItem(
              value: 'similar_username',
              child: Text(
                'اسم مستخدم وكلمة سر متشابهين',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
            DropdownMenuItem(
              value: 'unique_credentials',
              child: Text(
                'اسم مستخدم وكلمة سر مختلفين',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
          ],
          onChanged: (value) => setState(() => _generationType = value!),
          decoration: _buildInputDecoration('نوع التوليد'),
          dropdownColor: _cardColor,
          style: TextStyle(color: _textColor),
        ),
        const SizedBox(height: 16),
        // عناصر التحكم في حجم الخط
        Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    'حجم خط رمز الدخول',
                    style: TextStyle(
                      color: _textColor,
                      fontSize: 13,
                      fontFamily: 'Tajawal',
                    ),
                  ),
                  Slider(
                    value: _usernameFontSize,
                    min: 8,
                    max: 24,
                    divisions: 16,
                    label: _usernameFontSize.toStringAsFixed(1),
                    onChanged:
                        (value) => setState(() => _usernameFontSize = value),
                    activeColor: _primaryColor,
                    inactiveColor: _textColor.withOpacity(0.3),
                  ),
                ],
              ),
            ),
            if (_generationType != 'username_only') ...[
              SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'حجم خط كلمة السر',
                      style: TextStyle(
                        color: _textColor,
                        fontSize: 13,
                        fontFamily: 'Tajawal',
                      ),
                    ),
                    Slider(
                      value: _passwordFontSize,
                      min: 8,
                      max: 24,
                      divisions: 16,
                      label: _passwordFontSize.toStringAsFixed(1),
                      onChanged:
                          (value) => setState(() => _passwordFontSize = value),
                      activeColor: _primaryColor,
                      inactiveColor: _textColor.withOpacity(0.3),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: TextFormField(
                initialValue: _usernameDigitsCount.toString(),
                keyboardType: TextInputType.number,
                decoration: _buildInputDecoration('عدد خانات اسم المستخدم'),
                style: TextStyle(color: _textColor),
                validator: (value) {
                  if (value == null ||
                      value.isEmpty ||
                      int.tryParse(value) == null ||
                      int.parse(value) <= 0) {
                    return 'يجب إدخال عدد صحيح موجب';
                  }
                  return null;
                },
                onChanged:
                    (value) => setState(
                      () => _usernameDigitsCount = int.tryParse(value) ?? 7,
                    ),
              ),
            ),
            if (_generationType == 'unique_credentials') SizedBox(width: 16),
            if (_generationType == 'unique_credentials')
              Expanded(
                child: TextFormField(
                  initialValue: _passwordDigitsCount.toString(),
                  keyboardType: TextInputType.number,
                  decoration: _buildInputDecoration('عدد خانات كلمة المرور'),
                  style: TextStyle(color: _textColor),
                  validator: (value) {
                    if (value == null ||
                        value.isEmpty ||
                        int.tryParse(value) == null ||
                        int.parse(value) <= 0) {
                      return 'يجب إدخال عدد صحيح موجب';
                    }
                    return null;
                  },
                  onChanged:
                      (value) => setState(
                        () => _passwordDigitsCount = int.tryParse(value) ?? 8,
                      ),
                ),
              ),
          ],
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _profile,
          items:
              _availableProfiles
                  .map(
                    (profile) => DropdownMenuItem(
                      value: profile,
                      child: Text(
                        profile,
                        style: TextStyle(
                          color: _textColor,
                          fontFamily: 'Tajawal',
                        ),
                      ),
                    ),
                  )
                  .toList(),
          onChanged: (value) => setState(() => _profile = value!),
          decoration: _buildInputDecoration('بروفايل الهوتسبوت'),
          dropdownColor: _cardColor,
          style: TextStyle(color: _textColor),
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _usernamePrefix,
          maxLength: 2,
          decoration: _buildInputDecoration('بادئة اسم المستخدم (1-2 أحرف)'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty) return 'يجب إدخال بادئة';
            return null;
          },
          onChanged: (value) => setState(() => _usernamePrefix = value),
        ),
        const SizedBox(height: 16),

        TextFormField(
          initialValue: _validityDays.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration('مدة الصلاحية (أيام)'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty || int.tryParse(value) == null)
              return 'يجب إدخال عدد صحيح';
            return null;
          },
          onChanged:
              (value) =>
                  setState(() => _validityDays = int.tryParse(value) ?? 30),
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: TextFormField(
                initialValue: _limitBytes.toString(),
                keyboardType: TextInputType.number,
                decoration: _buildInputDecoration(
                  'الكمية',
                  hintText: 'مثال: 20',
                ),
                style: TextStyle(color: _textColor),
                onChanged:
                    (value) =>
                        setState(() => _limitBytes = int.tryParse(value) ?? 0),
              ),
            ),
            const SizedBox(width: 8),
            DropdownButton<String>(
              value: _dataUnit,
              items: const [
                DropdownMenuItem(
                  value: 'MB',
                  child: Text(
                    'ميغابايت',
                    style: TextStyle(fontFamily: 'Tajawal'),
                  ),
                ),
                DropdownMenuItem(
                  value: 'GB',
                  child: Text(
                    'جيجابايت',
                    style: TextStyle(fontFamily: 'Tajawal'),
                  ),
                ),
              ],
              onChanged: (value) => setState(() => _dataUnit = value!),
              dropdownColor: _cardColor,
              style: TextStyle(color: _textColor),
            ),
          ],
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _limitHours.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration('عدد الساعات'),
          style: TextStyle(color: _textColor),
          onChanged:
              (value) => setState(() => _limitHours = int.tryParse(value) ?? 0),
        ),
      ],
    );
  }

  Future<void> _fetchFirstSerialNumber() async {
    setState(() {
      _isLoading = true;
      _progressMessage = 'جلب الرقم التسلسلي الأول...';
    });

    try {
      final response = await widget.client.talk([
        '/ip/hotspot/user/print',
        '?profile=$_profile',
        '=.proplist=.id',
        '=.limit=1',
        '=.order=creation-time',
      ]);

      if (response.isNotEmpty) {
        final id = response.first['.id'] as String;
        final parts = id.split('*');
        if (parts.length > 1) {
          final hexPart = parts[1];
          setState(() {
            _firstSerialNumber = int.tryParse(hexPart, radix: 16) ?? 0;
          });
        }
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'خطأ في جلب الرقم التسلسلي',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  String _getNextSerialNumber() {
    _currentSerialNumber++;
    return '${_firstSerialNumber + _currentSerialNumber}';
  }

  Widget _buildDesignCard(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    return Container(
      decoration: BoxDecoration(
        color: _cardColor,
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: _textColor.withOpacity(0.1)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2),
            blurRadius: 10,
            offset: const Offset(0, 5),
          ),
        ],
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'تصميم الكرت',
              style: TextStyle(
                fontFamily: 'Tajawal',
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: _textColor,
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: _pickBackgroundImage,
              icon: Icon(Icons.image, color: _textColor),
              label: Text(
                'اختر صورة خلفية',
                style: TextStyle(color: _textColor, fontFamily: 'Tajawal'),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
                elevation: 3,
                shadowColor: _primaryColor.withOpacity(0.3),
              ),
            ),
            const SizedBox(height: 16),

            if (_includeSerialNumber) ...[
              SizedBox(height: 16),
              Text(
                'حجم الخط للرقم التسلسلي',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: _textColor,
                  fontSize: 16,
                  fontWeight: FontWeight.w500,
                ),
              ),
              Slider(
                value: _serialNumberFontSize,
                min: 6,
                max: 20,
                divisions: 14,
                label: _serialNumberFontSize.toStringAsFixed(1),
                onChanged:
                    (value) => setState(() => _serialNumberFontSize = value),
                activeColor: _primaryColor,
                inactiveColor: _textColor.withOpacity(0.3),
              ),
            ],
            Container(
              width: double.infinity,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: _textColor.withOpacity(0.05),
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: _textColor.withOpacity(0.2)),
              ),
              child: Column(
                children: [
                  LayoutBuilder(
                    builder: (context, constraints) {
                      final previewWidth = min(
                        constraints.maxWidth - 32,
                        _previewCardWidth,
                      );
                      final previewHeight =
                          previewWidth *
                          (_previewCardHeight / _previewCardWidth);

                      return Container(
                        width: previewWidth,
                        height: previewHeight,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(8),
                          image:
                              _backgroundImage != null
                                  ? DecorationImage(
                                    image: FileImage(_backgroundImage!),
                                    fit: BoxFit.contain,
                                  )
                                  : null,
                          color:
                              _backgroundImage == null
                                  ? _textColor.withOpacity(0.1)
                                  : null,
                          border: Border.all(
                            color: _textColor.withOpacity(0.3),
                          ),
                        ),
                        child: Stack(
                          children: [
                            if (_backgroundImage == null)
                              Center(
                                child: Text(
                                  'لا توجد صورة خلفية',
                                  style: TextStyle(fontFamily: 'Tajawal'),
                                ),
                              ),
                            Positioned(
                              left: _usernamePosition.dx * previewWidth,
                              top: _usernamePosition.dy * previewHeight,
                              child: GestureDetector(
                                onTap:
                                    () => setState(
                                      () => _selectedElement = 'username',
                                    ),
                                onPanUpdate: (details) {
                                  setState(() {
                                    _usernamePosition = Offset(
                                      (_usernamePosition.dx +
                                              details.delta.dx / previewWidth)
                                          .clamp(0.0, 1.0),
                                      (_usernamePosition.dy +
                                              details.delta.dy / previewHeight)
                                          .clamp(0.0, 1.0),
                                    );
                                    _selectedElement = 'username';
                                  });
                                },
                                child: Container(
                                  padding: const EdgeInsets.fromLTRB(
                                    6,
                                    1,
                                    6,
                                    1,
                                  ),
                                  decoration: BoxDecoration(
                                    color: Colors.white.withOpacity(0.7),
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  child: Text(
                                    (_tabController?.index ?? 0) == 0
                                        ? _username
                                        : 'رمز الدخول',
                                    style: TextStyle(
                                      fontFamily: 'Tajawal',
                                      color: Colors.black,
                                      fontSize:
                                          constraints.maxWidth < 400 ? 14 : 16,
                                      fontWeight: FontWeight.bold,
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            if (_includeSerialNumber)
                              Positioned(
                                left: _serialNumberPosition.dx * previewWidth,
                                top: _serialNumberPosition.dy * previewHeight,
                                child: GestureDetector(
                                  onPanUpdate: (details) {
                                    setState(() {
                                      _serialNumberPosition = Offset(
                                        (_serialNumberPosition.dx +
                                                details.delta.dx / previewWidth)
                                            .clamp(0.0, 1.0),
                                        (_serialNumberPosition.dy +
                                                details.delta.dy /
                                                    previewHeight)
                                            .clamp(0.0, 1.0),
                                      );
                                      _selectedElement = 'serial';
                                    });
                                  },
                                  onTap:
                                      () => setState(
                                        () => _selectedElement = 'serial',
                                      ),
                                  child: Container(
                                    padding: EdgeInsets.fromLTRB(6, 1, 6, 1),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.7),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      _firstSerialNumber > 0
                                          ? '${_firstSerialNumber + _currentSerialNumber}'
                                          : '123',
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: Colors.black,
                                        fontSize: _serialNumberFontSize + 3,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                            if (_generationType == 'unique_credentials')
                              Positioned(
                                left: _passwordPosition.dx * previewWidth,
                                top: _passwordPosition.dy * previewHeight,
                                child: GestureDetector(
                                  onPanUpdate: (details) {
                                    setState(() {
                                      _passwordPosition = Offset(
                                        (_passwordPosition.dx +
                                                details.delta.dx / previewWidth)
                                            .clamp(0.0, 1.0),
                                        (_passwordPosition.dy +
                                                details.delta.dy /
                                                    previewHeight)
                                            .clamp(0.0, 1.0),
                                      );
                                      _selectedElement = 'password';
                                    });
                                  },
                                  onTap:
                                      () => setState(
                                        () => _selectedElement = 'password',
                                      ),
                                  child: Container(
                                    padding: const EdgeInsets.fromLTRB(
                                      6,
                                      1,
                                      6,
                                      1,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Colors.white.withOpacity(0.7),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      'كلمة السر',
                                      style: TextStyle(
                                        fontFamily: 'Tajawal',
                                        color: Colors.black,
                                        fontSize:
                                            constraints.maxWidth < 400
                                                ? 14
                                                : 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ),
                              ),
                          ],
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 16),

                  // عرض عناوين التحكم لكل عنصر
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // نص يوضح العنصر المحدد
                      Padding(
                        padding: const EdgeInsets.only(bottom: 8.0),
                        child: Text(
                          _selectedElement == null
                              ? 'اختر عنصر للتحكم'
                              : _selectedElement == 'username'
                              ? 'التحكم في رمز الدخول'
                              : _selectedElement == 'password'
                              ? 'التحكم في كلمة السر'
                              : 'التحكم في الرقم التسلسلي',
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor,
                            fontSize: 16,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ),

                      // أزرار التحكم
                      Center(
                        child: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.1),
                            borderRadius: BorderRadius.circular(16),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              _buildDirectionButton(
                                icon: Icons.keyboard_arrow_up,
                                onPressed: () {
                                  if (_selectedElement == 'username') {
                                    _updatePosition(false, true, 0.01);
                                  } else if (_selectedElement == 'password') {
                                    _updatePosition(
                                      false,
                                      true,
                                      0.01,
                                      isPassword: true,
                                    );
                                  } else if (_selectedElement == 'serial') {
                                    _updatePosition(
                                      false,
                                      true,
                                      0.01,
                                      isSerial: true,
                                    );
                                  }
                                },
                              ),
                              const SizedBox(width: 8),
                              _buildDirectionButton(
                                icon: Icons.keyboard_arrow_right,
                                onPressed: () {
                                  if (_selectedElement == 'username') {
                                    _updatePosition(true, false, 0.01);
                                  } else if (_selectedElement == 'password') {
                                    _updatePosition(
                                      true,
                                      false,
                                      0.01,
                                      isPassword: true,
                                    );
                                  } else if (_selectedElement == 'serial') {
                                    _updatePosition(
                                      true,
                                      false,
                                      0.01,
                                      isSerial: true,
                                    );
                                  }
                                },
                              ),
                              const SizedBox(width: 8),
                              _buildDirectionButton(
                                icon: Icons.keyboard_arrow_left,
                                onPressed: () {
                                  if (_selectedElement == 'username') {
                                    _updatePosition(true, false, -0.01);
                                  } else if (_selectedElement == 'password') {
                                    _updatePosition(
                                      true,
                                      false,
                                      -0.01,
                                      isPassword: true,
                                    );
                                  } else if (_selectedElement == 'serial') {
                                    _updatePosition(
                                      true,
                                      false,
                                      -0.01,
                                      isSerial: true,
                                    );
                                  }
                                },
                              ),
                              const SizedBox(width: 8),
                              _buildDirectionButton(
                                icon: Icons.keyboard_arrow_down,
                                onPressed: () {
                                  if (_selectedElement == 'username') {
                                    _updatePosition(false, true, -0.01);
                                  } else if (_selectedElement == 'password') {
                                    _updatePosition(
                                      false,
                                      true,
                                      -0.01,
                                      isPassword: true,
                                    );
                                  } else if (_selectedElement == 'serial') {
                                    _updatePosition(
                                      false,
                                      true,
                                      -0.01,
                                      isSerial: true,
                                    );
                                  }
                                },
                              ),
                            ],
                          ),
                        ),
                      ),

                      const SizedBox(height: 12),

                      // نص إرشادي
                      Text(
                        'يمكنك تحريك العناصر إما بالسحب والإفلات أو باستخدام الأزرار',
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: Colors.white.withOpacity(0.7),
                          fontSize: 12,
                          fontStyle: FontStyle.italic,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildLoadingOverlay() {
    return Positioned.fill(
      child: Container(
        color: Colors.black54,
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const CircularProgressIndicator(color: Colors.white),
              const SizedBox(height: 20),
              Text(
                _progressMessage,
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                  fontFamily: 'Tajawal',
                ),
              ),
              const SizedBox(height: 10),
              if (_progress > 0)
                SizedBox(
                  width: 300,
                  child: LinearProgressIndicator(
                    value: _progress,
                    backgroundColor: Colors.grey[800],
                    valueColor: const AlwaysStoppedAnimation<Color>(
                      Colors.white,
                    ),
                  ),
                ),
            ],
          ),
        ),
      ),
    );
  }

  // دالة مساعدة لإنشاء أزرار الاتجاه مع دعم النقر المطول
  // دالة مساعدة لإنشاء أزرار الاتجاه مع تحريك خطوة واحدة فقط
  Widget _buildDirectionButton({
    required IconData icon,
    required VoidCallback onPressed,
  }) {
    return IconButton(
      icon: Icon(icon, size: 28),
      color: _textColor,
      splashRadius: 20,
      onPressed: onPressed, // تنفيذ الحركة مرة واحدة فقط عند النقر
    );
  }

  // دالة مساعدة لتحديث الموضع
  void _updatePosition(
    bool isVertical,
    bool isNegative,
    double value, {
    bool isPassword = false,
    bool isSerial = false,
  }) {
    setState(() {
      final delta = value * (isNegative ? -1 : 1);

      if (isSerial) {
        _serialNumberPosition = Offset(
          isVertical
              ? (_serialNumberPosition.dx + delta).clamp(0.0, 1.0)
              : _serialNumberPosition.dx,
          !isVertical
              ? (_serialNumberPosition.dy + delta).clamp(0.0, 1.0)
              : _serialNumberPosition.dy,
        );
      } else if (isPassword) {
        _passwordPosition = Offset(
          isVertical
              ? (_passwordPosition.dx + delta).clamp(0.0, 1.0)
              : _passwordPosition.dx,
          !isVertical
              ? (_passwordPosition.dy + delta).clamp(0.0, 1.0)
              : _passwordPosition.dy,
        );
      } else {
        _usernamePosition = Offset(
          isVertical
              ? (_usernamePosition.dx + delta).clamp(0.0, 1.0)
              : _usernamePosition.dx,
          !isVertical
              ? (_usernamePosition.dy + delta).clamp(0.0, 1.0)
              : _usernamePosition.dy,
        );
      }
    });
  }

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

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

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

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

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

  Widget _buildSettingsCard(String title, Widget child) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.05),
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: Colors.white.withOpacity(0.1)),
      ),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              title,
              style: const TextStyle(
                fontFamily: 'Tajawal',
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: Colors.white,
              ),
            ),
            const SizedBox(height: 16),
            child,
          ],
        ),
      ),
    );
  }
}


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