في هذا الكود
import 'dart:async';
import 'dart:convert';
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/AddHotspotUser.dart';
import 'package:micro_panel/HomePage.dart';
import 'package:micro_panel/Login.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:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:router_os_client/router_os_client.dart';
import 'package:url_launcher/url_launcher.dart';

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

  @override
  State<AddUserManagerCards> createState() => _AddUserManagerCardsState();
}

class _AddUserManagerCardsState extends State<AddUserManagerCards>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;

  final _singleUserFormKey = GlobalKey<FormState>();
  final _multiUserFormKey = GlobalKey<FormState>();
  bool _showCounter = false;
  int _successfulCards = 0;
  int _failedCards = 0;
  int _numberOfCards = 45;
  String _usernamePrefix = '';
  String _username = '';
  String _password = '';
  bool _restrictOnFirstLogin = true;

  bool _includeSerialNumber = false;
  Offset _serialNumberPosition = Offset(0.1, 0.1);
  double _serialNumberFontSize = 6.0;
  String _serialNumberPrefix = '';
  int _currentSerialNumber = 0;
  int _firstSerialNumber = 0;
  String? _selectedElement;

  String? _profile;
  List<String> _availableProfiles = [];

  bool _isLoading = false;
  double _progress = 0.0;
  String _progressMessage = '';

  File? _backgroundImage;
  Uint8List? _imageBytes;

  // Position of displayed username on card preview
  Offset _passwordPosition = const Offset(0.5, 0.6); // يجب إضافة هذا المتغير
  Offset _usernamePosition = const Offset(0.5, 0.5);
  double _usernameFontSize = 12.0;
  double _passwordFontSize = 12.0;

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

  // Generation type for multiple users
  // 'username_only', 'similar_username', 'unique_credentials'
  String _generationType = 'username_only';

  List<Map<String, String>> _generatedCards = [];

  int _rowsPerPage = 15;
  int _columnsPerPage = 3;
  double _previewCardWidth = 400;
  double _previewCardHeight = 250;
  int _usernameDigitsCount = 7;
  int _passwordDigitsCount = 8;

  final Color _primaryColor = const Color(0xFF3B82F6);
  final Color _backgroundColor = const Color(0xFF0A192F);
  final Color _cardColor = const Color(0xFF172A46);
  final Color _textColor = Colors.white;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(
      length: 2,
      vsync: this,
      initialIndex: widget.initialTab,
    );
    _loadSavedValues();
    _loadPositionsFromJson();
    _fetchUserManagerProfiles();
  }

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

  Future<void> _savePositionsToJson() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/card_positions.json');

      await file.writeAsString(
        jsonEncode({
          'usernamePosition': {
            'dx': _usernamePosition.dx,
            'dy': _usernamePosition.dy,
          },
          'passwordPosition': {
            'dx': _passwordPosition.dx,
            'dy': _passwordPosition.dy,
          },
          'serialNumberPosition': {
            'dx': _serialNumberPosition.dx,
            'dy': _serialNumberPosition.dy,
          },
          'usernameFontSize': _usernameFontSize,
          'passwordFontSize': _passwordFontSize,
          'serialNumberFontSize': _serialNumberFontSize,
          'usernameDigitsCount': _usernameDigitsCount,
          'passwordDigitsCount': _passwordDigitsCount,
          'usernamePrefix': _usernamePrefix,
          'includeSerialNumber': _includeSerialNumber,
        }),
      );
    } catch (e) {
      print('حدث خطأ في حفظ الموقع على الصورة');
    }
  }

  // دالة لتحميل المواقع من ملف JSON
  Future<void> _loadPositionsFromJson() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/card_positions.json');

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

        // طباعة محتوى الملف للتأكد من البيانات
        print('محتويات ملف JSON: $jsonData');

        // استخدام القيم الافتراضية إذا كانت القيم غير موجودة أو غير صالحة
        final usernameDx = _parseDouble(
          jsonData['usernamePosition']?['dx'],
          0.5,
        );
        final usernameDy = _parseDouble(
          jsonData['usernamePosition']?['dy'],
          0.5,
        );
        final passwordDx = _parseDouble(
          jsonData['passwordPosition']?['dx'],
          0.5,
        );
        final passwordDy = _parseDouble(
          jsonData['passwordPosition']?['dy'],
          0.6,
        );
        final serialDx = _parseDouble(
          jsonData['serialNumberPosition']?['dx'],
          0.1,
        );
        final serialDy = _parseDouble(
          jsonData['serialNumberPosition']?['dy'],
          0.1,
        );

        setState(() {
          _usernamePosition = Offset(usernameDx, usernameDy);
          _passwordPosition = Offset(passwordDx, passwordDy);
          _serialNumberPosition = Offset(serialDx, serialDy);
          _usernameFontSize = _parseDouble(jsonData['usernameFontSize'], 12.0);
          _passwordFontSize = _parseDouble(jsonData['passwordFontSize'], 12.0);
          _serialNumberFontSize = _parseDouble(
            jsonData['serialNumberFontSize'],
            6.0,
          );
          _usernameDigitsCount = _parseInt(jsonData['usernameDigitsCount'], 7);
          _passwordDigitsCount = _parseInt(jsonData['passwordDigitsCount'], 8);
          _usernamePrefix = jsonData['usernamePrefix']?.toString() ?? '';
          _includeSerialNumber = jsonData['includeSerialNumber'] == true;
        });

        // طباعة القيم المحملة للتأكد
        print('''
      القيم المحملة:
      usernamePosition: ${_usernamePosition}
      passwordPosition: ${_passwordPosition}
      serialNumberPosition: ${_serialNumberPosition}
      usernameFontSize: ${_usernameFontSize}
      passwordFontSize: ${_passwordFontSize}
      serialNumberFontSize: ${_serialNumberFontSize}
      usernameDigitsCount: ${_usernameDigitsCount}
      passwordDigitsCount: ${_passwordDigitsCount}
      usernamePrefix: $_usernamePrefix
      includeSerialNumber: $_includeSerialNumber
      ''');
      } else {
        print('ملف المواقع غير موجود، سيتم استخدام القيم الافتراضية');
      }
    } catch (e, stackTrace) {
      print('حدث خطأ في جلب موقع البيانات على الصورة: $e');
      print('Stack trace: $stackTrace');
    }
  }

  // دالة مساعدة لتحليل القيم الرقمية
  double _parseDouble(dynamic value, double defaultValue) {
    if (value == null) return defaultValue;
    if (value is double) return value;
    if (value is int) return value.toDouble();
    if (value is String) return double.tryParse(value) ?? defaultValue;
    return defaultValue;
  }

  // دالة مساعدة لتحليل القيم الصحيحة
  int _parseInt(dynamic value, int defaultValue) {
    if (value == null) return defaultValue;
    if (value is int) return value;
    if (value is double) return value.toInt();
    if (value is String) return int.tryParse(value) ?? defaultValue;
    return defaultValue;
  }

  Future<void> _loadSavedValues() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/user_manager_settings.json');

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

        setState(() {
          _numberOfCards = jsonData['numberOfCards'] ?? 0;
          _usernamePrefix = jsonData['usernamePrefix'] ?? '';
          _password = jsonData['password'] ?? '';
          // يمكنك إضافة المزيد من الحقول هنا حسب الحاجة
        });
      }
    } catch (e) {
      print('Error loading saved values: $e');
    }
  }

  // أضف هذه الدالة لحفظ القيم عند التغيير
  Future<void> _saveValues() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/user_manager_settings.json');

      await file.writeAsString(
        jsonEncode({
          'numberOfCards': _numberOfCards,
          'usernamePrefix': _usernamePrefix,
          'password': _password,
          // يمكنك إضافة المزيد من الحقول هنا حسب الحاجة
        }),
      );
    } catch (e) {
      print('Error saving values: $e');
    }
  }

  Future<int> _getRouterVersion() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/router_version.json');

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

        // طباعة محتوى الملف كـ String
        print('محتوى الملف كـ String: $content');

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

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

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

  /// جلب البروفايلات من اليوزر مانجر
  Future<void> _fetchUserManagerProfiles() async {
    setState(() {
      _isLoading = true;
      _progressMessage = 'جلب قائمة البروفايلات...';
    });

    try {
      // جلب إصدار الراوتر من الملف المحلي
      final routerVersion = await _getRouterVersion();
      final isVersion7 = routerVersion >= 7;

      // استخدام الأمر المناسب حسب الإصدار
      final response = await widget.client.talk([
        isVersion7
            ? '/user-manager/profile/print'
            : '/tool/user-manager/profile/print',
        '=detail=true',
        '=without-paging=true',
      ]);

      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> _fetchFirstSerialNumber() async {
    setState(() {
      _isLoading = true;
      _progressMessage = 'جلب الرقم التسلسلي الأول...';
    });

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

      final tempUsername = 'temp_user_${DateTime.now().millisecondsSinceEpoch}';

      // إضافة مستخدم مؤقت
      await widget.client.talk([
        isVersion7 ? '/user-manager/user/add' : '/tool/user-manager/user/add',
        isVersion7 ? '' : '=customer=admin',
        isVersion7 ? '=name=$tempUsername' : '=username=$tempUsername',
        '=password=temp123',
        '=disabled=yes',
        '=shared-users=1',
      ]);

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

      if (response.isNotEmpty) {
        final id = response.first['.id'] as String;

        await widget.client.talk([
          isVersion7
              ? '/user-manager/user/remove'
              : '/tool/user-manager/user/remove',
          '=numbers=$id',
        ]);

        // معالجة الـ ID بناءً على إصدار الروتر
        if (isVersion7) {
          // في الإصدار 7، قد يكون الـ ID رقمًا مباشرًا أو بتنسيق مختلف
          if (id.contains('*')) {
            final parts = id.split('*');
            if (parts.length > 1) {
              setState(() {
                _firstSerialNumber = int.tryParse(parts[1], radix: 16) ?? 0;
              });
            }
          } else {
            // إذا كان ID رقمًا مباشرًا
            setState(() {
              _firstSerialNumber = int.tryParse(id) ?? 0;
            });
          }
        } else {
          // للإصدارات القديمة (ما قبل 7)
          final parts = id.split('*');
          if (parts.length > 1) {
            setState(() {
              _firstSerialNumber = int.tryParse(parts[1], radix: 16) ?? 0;
            });
          }
        }
      }

      // حذف المستخدم المؤقت باستخدام اسم المستخدم بدلاً من الـ ID
      final responseRemove = await widget.client.talk([
        isVersion7
            ? '/user-manager/user/print'
            : '/tool/user-manager/user/print',
        isVersion7 ? '?name=$tempUsername' : '?username=$tempUsername',
        '=.proplist=.id',
      ]);
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'خطأ في جلب الرقم التسلسلي',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.red,
          ),
        );
      }
      setState(() => _firstSerialNumber = 0);
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

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

  /// توليد كلمة مرور عشوائية
  String _generateRandomPassword() {
    const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
    final random = Random.secure();
    return String.fromCharCodes(
      Iterable.generate(
        _passwordDigitsCount,
        (_) => chars.codeUnitAt(random.nextInt(chars.length)),
      ),
    );
  }

  /// توليد اسم مستخدم فقط (لكل مستخدم)
  String _generateUsernameOnly(int index, Set<String> usedUsernames) {
    final random = Random();
    String username;
    do {
      final number = random.nextInt(pow(10, _usernameDigitsCount).toInt());
      username =
          '$_usernamePrefix${number.toString().padLeft(_usernameDigitsCount, '0')}';
    } while (usedUsernames.contains(username));
    usedUsernames.add(username);
    return username;
  }

  /// توليد اسم مستخدم وكلمة مرور متشابهة
  Map<String, String> _generateSimilarCredentials(
    int index,
    Set<String> usedUsernames,
  ) {
    final random = Random();
    String username;
    do {
      final number = random.nextInt(pow(10, _usernameDigitsCount).toInt());
      username =
          '$_usernamePrefix${number.toString().padLeft(_usernameDigitsCount, '0')}';
    } while (usedUsernames.contains(username));
    usedUsernames.add(username);
    return {'username': username, 'password': username};
  }

  /// توليد اسم مستخدم وكلمة مرور مختلفتين
  Map<String, String> _generateUniqueCredentials(
    int index,
    Set<String> usedUsernames,
  ) {
    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 (usedUsernames.contains(username));
    usedUsernames.add(username);

    return {'username': username, 'password': password};
  }

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

  Future<void> _generateUserManagerCards() async {
    _currentSerialNumber = 0;
    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 {
        await _fetchFirstSerialNumber();
      } catch (e) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'خطأ في جلب الرقم التسلسلي',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
              backgroundColor: Colors.red,
            ),
          );
        }
        return;
      } finally {
        setState(() => _isLoading = false);
      }
    }

    if (_profile == null || _profile!.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'الرجاء اختيار البروفايل',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (_tabController.index == 1 && _backgroundImage == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text(
            'الرجاء اختيار صورة خلفية أولا',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    setState(() {
      _isLoading = true;
      _progress = 0.0;
      _progressMessage = 'بدء إنشاء المستخدمين...';
      _generatedCards.clear();
      _showCounter = true;
      _successfulCards = 0;
      _failedCards = 0;
    });

    final Set<String> uniqueUsernames = {};

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

      if (_tabController.index == 0) {
        // إضافة مستخدم واحد
        final commands = [
          isVersion7 ? '/user-manager/user/add' : '/tool/user-manager/user/add',
          isVersion7 ? '' : '=customer=admin',
          isVersion7 ? '=name=$_username' : '=username=$_username',
          '=disabled=no',
          if (_password.isNotEmpty) '=password=$_password',
          '=shared-users=1',
          if (_restrictOnFirstLogin)
            isVersion7 ? '=caller-id=bind' : '=caller-id-bind-on-first-use=yes',
        ];

        await widget.client.talk(commands);

        // تفعيل البروفايل
        if (isVersion7) {
          await widget.client.talk([
            '/user-manager/user-profile/add',
            '=profile=$_profile',
            '=user=$_username',
          ]);
        } else {
          await widget.client.talk([
            '/tool/user-manager/user/create-and-activate-profile',
            '=customer=admin',
            '=profile=$_profile',
            '=numbers=$_username',
          ]);
        }

        _generatedCards.add({'username': _username, 'password': _password});
        setState(() {
          _successfulCards++;
          _progress = 1.0;
          _progressMessage = 'تم إنشاء المستخدم بنجاح.';
        });
        // بعد نجاح إنشاء المستخدم
        if (_tabController.index == 0 &&
            _selectedSendMethod != 'none' &&
            _phoneNumberController.text.isNotEmpty) {
          await _sendUserCredentials();
        }
      } else {
        // إضافة مستخدمين متعددين
        final List<String> generatedUsernames = [];

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

            if (_generationType == 'username_only') {
              username = _generateUsernameOnly(i, uniqueUsernames);
              password = '';
            } else if (_generationType == 'similar_username') {
              final cred = _generateSimilarCredentials(i, uniqueUsernames);
              username = cred['username']!;
              password = cred['password']!;
            } else {
              final cred = _generateUniqueCredentials(i, uniqueUsernames);
              username = cred['username']!;
              password = cred['password']!;
            }

            // إضافة المستخدم
            await widget.client.talk([
              isVersion7
                  ? '/user-manager/user/add'
                  : '/tool/user-manager/user/add',
              isVersion7 ? '' : '=customer=admin',
              isVersion7 ? '=name=$username' : '=username=$username',
              '=disabled=no',
              if (password.isNotEmpty) '=password=$password',
              '=shared-users=1',
              if (_restrictOnFirstLogin)
                isVersion7
                    ? '=caller-id=bind'
                    : '=caller-id-bind-on-first-use=yes',
            ]);

            generatedUsernames.add(username);
            _generatedCards.add({'username': username, 'password': password});
            setState(() {
              _successfulCards++;
              _progress = (i + 1) / _numberOfCards;
              _progressMessage =
                  'جاري إضافة المستخدمين... ${i + 1}/$_numberOfCards';
            });
          } catch (e) {
            setState(() => _failedCards++);
            continue;
          }
        }

        // تفعيل البروفايل لجميع المستخدمين
        if (generatedUsernames.isNotEmpty) {
          try {
            if (isVersion7) {
              for (final username in generatedUsernames) {
                await widget.client.talk([
                  '/user-manager/user-profile/add',
                  '=profile=$_profile',
                  '=user=$username',
                ]);
              }
            } else {
              await widget.client.talk([
                '/tool/user-manager/user/create-and-activate-profile',
                '=customer=admin',
                '=profile=$_profile',
                '=numbers=${generatedUsernames.join(',')}',
              ]);
            }
          } catch (e) {
            // في حالة فشل تفعيل البروفايل، لا نعتبره فشلاً كاملاً
            print('Failed to activate profile');
          }
        }
      }

      await _generateAndSavePdf();
    } catch (e) {
      print('$e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text(
              'خطأ أثناء إنشاء المستخدمين',
              style: TextStyle(fontFamily: 'Tajawal'),
            ),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      await Future.delayed(const Duration(milliseconds: 500));
      setState(() {
        _isLoading = false;
        _progress = 0.0;
        _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),
          ),
        );
      }
    }
  }

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

  /// اختيار صورة الخلفية
  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();

      setState(() {
        _backgroundImage = file;
        _imageBytes = bytes;
      });

      // تحميل المواقع المحفوظة عند اختيار الصورة
      await _loadPositionsFromJson();
    }
  }

  /// إنشاء وحفظ ملف PDF للكروت
  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];

            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 + offsetX,
                        top:
                            _serialNumberPosition.dy * cardHeight +
                            offsetY +
                            17,
                        child: pw.Text(
                          _getNextSerialNumber(),
                          style: pw.TextStyle(
                            color: PdfColors.black,
                            fontSize: _serialNumberFontSize,
                            fontWeight: pw.FontWeight.bold,
                          ),
                        ),
                      ),
                    pw.Positioned(
                      left: _usernamePosition.dx * cardWidth + offsetX,
                      top: _usernamePosition.dy * cardHeight + offsetY,
                      child: pw.Text(
                        card['username']!,
                        style: pw.TextStyle(
                          color: PdfColors.black,
                          fontSize: _usernameFontSize,
                          fontWeight: pw.FontWeight.bold,
                        ),
                      ),
                    ),
                    if (_generationType == 'unique_credentials' &&
                        card['password']!.isNotEmpty &&
                        card['password'] != card['username'])
                      pw.Positioned(
                        left: _passwordPosition.dx * cardWidth + offsetX,
                        top: _passwordPosition.dy * cardHeight + offsetY + 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 savePath = await FilePicker.platform.getDirectoryPath();
      if (savePath == 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 = '$savePath/$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,
          ),
        );
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  InputDecoration _buildInputDecoration(String labelText, {String? hintText}) =>
      InputDecoration(
        labelText: labelText,
        hintText: hintText,
        labelStyle: TextStyle(
          fontFamily: 'Tajawal',
          color: _textColor.withOpacity(0.8),
        ),
        hintStyle: TextStyle(
          fontFamily: 'Tajawal',
          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),
      );

  @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(
                            fontFamily: 'Tajawal',
                            color: Colors.white,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                  ),
                  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: [
                            _buildSingleUserTab(),
                            _buildMultipleUsersTab(),
                          ],
                        ),
                        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(
                  fontFamily: 'Tajawal',
                  color: Colors.white.withOpacity(0.5),
                  fontSize: 12,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            _buildNavItem(
              icon: Icons.dashboard,
              title: 'لوحة التحكم',
              isActive: false,
              onTap: () {
                Navigator.pushReplacement(
                  context,
                  MaterialPageRoute(
                    builder:
                        (context) => RouterDetailsPage(client: widget.client),
                  ),
                );
              },
            ),

            // قسم الهوتسبوت (قابل للطي)
            _buildExpandableSection(
              title: 'إدارة الهوتسبوت',
              icon: Icons.wifi,
              initiallyExpanded: isHotspotExpanded,
              onExpansionChanged: (expanded) {
                setState(() {
                  isHotspotExpanded = expanded;
                });
              },
              children: [
                _buildNavItem(
                  icon: Icons.people,
                  title: 'قائمة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => UsersPage(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.person_add,
                  title: 'اضافة مستخدم',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddHotspotCardsPage(
                              client: widget.client,
                              initialTab: 0,
                            ),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.group_add,
                  title: 'اضافة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      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.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) =>
                                UserManagerUserList(client: widget.client),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.payment_rounded,
                  title: 'اضافة مستخدم',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 0,
                            ),
                      ),
                    );
                  },
                ),
                _buildNavItem(
                  icon: Icons.credit_score,
                  title: 'اضافة المستخدمين',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder:
                            (context) => AddUserManagerCards(
                              client: widget.client,
                              initialTab: 1,
                            ),
                      ),
                    );
                  },
                ),

                _buildNavItem(
                  icon: Icons.assignment,
                  title: 'السجلات',
                  isActive: false,
                  onTap: () {
                    Navigator.push(
                      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: () {},
                ),
                _buildNavItem(
                  icon: Icons.feedback,
                  title: 'إرسال ملاحظات',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.info_outline,
                  title: 'حول التطبيق',
                  isActive: false,
                  onTap: () {},
                ),
                _buildNavItem(
                  icon: Icons.logout,
                  title: 'تسجيل الخروج',
                  isActive: false,
                  onTap: () {
                    Navigator.pushReplacement(
                      context,
                      MaterialPageRoute(builder: (context) => Login()),
                    );
                  },
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

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

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

  Widget _buildMobileLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      appBar: AppBar(
        title: Text(
          'إضافة مستخدمين (يوزر مانجر)',
          style: TextStyle(
            fontFamily: 'Tajawal',
            color: _textColor,
            fontSize: 20,
          ),
        ),
        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: [_buildSingleUserTab(), _buildMultipleUsersTab()],
            ),
          ),
          if (_isLoading) _buildLoadingOverlay(),
        ],
      ),
    );
  }

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

  /// تبويب إنشاء مستخدم واحد
  // أضف هذه المتغيرات في أعلى الكلاس
  String _selectedSendMethod = 'none'; // 'none', 'whatsapp', 'sms'
  TextEditingController _phoneNumberController = TextEditingController();

  /// تبويب إنشاء مستخدم واحد
  Widget _buildSingleUserTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _singleUserFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildCardSettings('اضافة مستخدم', _buildSingleFormFields()),
            const SizedBox(height: 24),
            _buildSendOptionsSection(),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: _generateUserManagerCards,
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
              ),
              child: const Text(
                'إنشاء المستخدم',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// قسم خيارات الإرسال
  Widget _buildSendOptionsSection() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.05),
        borderRadius: BorderRadius.circular(15),
        border: Border.all(color: Colors.white.withOpacity(0.1)),
      ),
      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),
          RadioListTile<String>(
            title: Text(
              'لا ترسل',
              style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
            ),
            value: 'none',
            groupValue: _selectedSendMethod,
            onChanged: (value) => setState(() => _selectedSendMethod = value!),
            activeColor: _primaryColor,
          ),
          RadioListTile<String>(
            title: Text(
              'إرسال عبر WhatsApp',
              style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
            ),
            value: 'whatsapp',
            groupValue: _selectedSendMethod,
            onChanged: (value) => setState(() => _selectedSendMethod = value!),
            activeColor: _primaryColor,
          ),
          RadioListTile<String>(
            title: Text(
              'إرسال عبر SMS',
              style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
            ),
            value: 'sms',
            groupValue: _selectedSendMethod,
            onChanged: (value) => setState(() => _selectedSendMethod = value!),
            activeColor: _primaryColor,
          ),
          if (_selectedSendMethod != 'none')
            Padding(
              padding: const EdgeInsets.only(top: 16),
              child: TextFormField(
                controller: _phoneNumberController,
                keyboardType: TextInputType.phone,
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                decoration: _buildInputDecoration('رقم الهاتف'),
                validator: (value) {
                  if (_selectedSendMethod != 'none' &&
                      (value == null || value.trim().isEmpty)) {
                    return 'يجب إدخال رقم الهاتف';
                  }
                  return null;
                },
              ),
            ),
        ],
      ),
    );
  }

  /// حقول نموذج المستخدم الواحد
  Widget _buildSingleFormFields() {
    return Column(
      children: [
        TextFormField(
          initialValue: _username,
          style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
          decoration: _buildInputDecoration('اسم المستخدم'),
          validator: (value) {
            if (value == null || value.trim().isEmpty) {
              return 'يجب إدخال اسم المستخدم';
            }
            return null;
          },
          onChanged: (val) => setState(() => _username = val.trim()),
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _password,
          obscureText: true,
          style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
          decoration: _buildInputDecoration('كلمة المرور (اختيارية)'),
          onChanged: (val) {
            setState(() => _password = val.trim());
            _saveValues();
          },
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _profile,
          style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
          items:
              _availableProfiles
                  .map(
                    (p) => DropdownMenuItem(
                      value: p,
                      child: Text(
                        p,
                        style: TextStyle(
                          fontFamily: 'Tajawal',
                          color: _textColor,
                        ),
                      ),
                    ),
                  )
                  .toList(),
          onChanged: (val) => setState(() => _profile = val),
          decoration: _buildInputDecoration('اختر البروفايل'),
          dropdownColor: _cardColor,
        ),
        const SizedBox(height: 16),
        SwitchListTile(
          title: Text(
            'تقييد حسب أول تسجيل دخول',
            style: TextStyle(
              fontFamily: 'Tajawal',
              color: _textColor,
              fontWeight: FontWeight.w600,
            ),
          ),
          subtitle: Text(
            _restrictOnFirstLogin
                ? 'سيتم تقييد المستخدم بأول جهاز يقوم بالتسجيل'
                : 'لن يتم تقييد المستخدم بأول جهاز يقوم بالتسجيل',
            style: TextStyle(
              fontFamily: 'Tajawal',
              color: _textColor.withOpacity(0.7),
              fontSize: 13,
            ),
          ),
          value: _restrictOnFirstLogin,
          onChanged: (value) => setState(() => _restrictOnFirstLogin = value),
          activeColor: _primaryColor,
          activeTrackColor: _primaryColor.withOpacity(0.3),
          dense: true,
          contentPadding: EdgeInsets.symmetric(horizontal: 12),
        ),
      ],
    );
  }

  Future<void> _sendUserCredentials() async {
    final phoneNumber = _phoneNumberController.text.trim();
    final message =
        'بيانات الدخول:\nاسم المستخدم: $_username\nكلمة المرور: $_password';

    try {
      if (_selectedSendMethod == 'whatsapp') {
        final whatsappUrl =
            "https://wa.me/$phoneNumber?text=${Uri.encodeComponent(message)}";
        if (await canLaunch(whatsappUrl)) {
          await launch(whatsappUrl);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'تعذر فتح WhatsApp',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
              backgroundColor: Colors.red,
            ),
          );
        }
      } else if (_selectedSendMethod == 'sms') {
        final smsUrl = "sms:$phoneNumber?body=${Uri.encodeComponent(message)}";
        if (await canLaunch(smsUrl)) {
          await launch(smsUrl);
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text(
                'تعذر فتح تطبيق الرسائل',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
              backgroundColor: Colors.red,
            ),
          );
        }
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(
            'حدث خطأ أثناء محاولة الإرسال',
            style: TextStyle(fontFamily: 'Tajawal'),
          ),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  /// تبويب إنشاء مجموعة مستخدمين
  Widget _buildMultipleUsersTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _multiUserFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            _buildCardSettings(
              'اضافة مجموعة مستخدمين',
              Column(
                children: [
                  TextFormField(
                    initialValue: _numberOfCards.toString(),
                    keyboardType: TextInputType.number,
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                    decoration: _buildInputDecoration('عدد المستخدمين'),
                    validator: (value) {
                      if (value == null ||
                          value.isEmpty ||
                          int.tryParse(value) == null ||
                          int.parse(value) <= 0) {
                        return 'يجب إدخال عدد صحيح موجب';
                      }
                      return null;
                    },
                    onChanged: (val) {
                      setState(() => _numberOfCards = int.tryParse(val) ?? 45);
                      _saveValues(); // حفظ القيم عند التغيير
                    },
                  ),
                  const SizedBox(height: 16),
                  DropdownButtonFormField<String>(
                    value: _generationType,
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                    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: (val) {
                      setState(() => _generationType = val!);
                    },
                    decoration: _buildInputDecoration('نوع التوليد'),
                    dropdownColor: _cardColor,
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'حجم خط اسم المستخدم',
                              style: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor,
                                fontSize: 13,
                              ),
                            ),
                            Slider(
                              value: _usernameFontSize,
                              min: 8,
                              max: 24,
                              divisions: 16,
                              label: _usernameFontSize.toStringAsFixed(1),
                              onChanged: (value) {
                                setState(() => _usernameFontSize = value);
                                _savePositionsToJson();
                              },
                              activeColor: _primaryColor,
                              inactiveColor: _textColor.withOpacity(0.3),
                            ),
                          ],
                        ),
                      ),
                      if (_generationType != 'username_only') ...[
                        SizedBox(width: 16),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                'حجم خط كلمة السر',
                                style: TextStyle(
                                  fontFamily: 'Tajawal',
                                  color: _textColor,
                                  fontSize: 13,
                                ),
                              ),
                              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),
                  Column(
                    children: [
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              initialValue: _usernamePrefix,
                              maxLength: 2,
                              style: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor,
                              ),
                              decoration: _buildInputDecoration(
                                'بادئة اسم المستخدم',
                              ),
                              validator: (value) {
                                if (value == null || value.trim().isEmpty) {
                                  return 'يجب إدخال بادئة اسم المستخدم';
                                }
                                return null;
                              },
                              onChanged: (val) {
                                setState(() => _usernamePrefix = val.trim());
                                _savePositionsToJson();
                              },
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(width: 16),
                      Row(
                        children: [
                          Expanded(
                            child: TextFormField(
                              initialValue: _usernameDigitsCount.toString(),
                              keyboardType: TextInputType.number,
                              style: TextStyle(
                                fontFamily: 'Tajawal',
                                color: _textColor,
                              ),
                              decoration: _buildInputDecoration(
                                'عدد خانات اسم المستخدم',
                              ),
                              validator: (value) {
                                if (value == null ||
                                    value.isEmpty ||
                                    int.tryParse(value) == null ||
                                    int.parse(value) <= 0) {
                                  return 'يجب إدخال عدد صحيح موجب';
                                }
                                return null;
                              },
                              onChanged: (val) {
                                setState(
                                  () =>
                                      _usernameDigitsCount =
                                          int.tryParse(val) ?? 7,
                                );
                                _savePositionsToJson();
                              },
                            ),
                          ),
                        ],
                      ),
                      if (_generationType == 'unique_credentials')
                        const SizedBox(height: 16),
                      if (_generationType == 'unique_credentials')
                        TextFormField(
                          initialValue: _passwordDigitsCount.toString(),
                          keyboardType: TextInputType.number,
                          style: TextStyle(
                            fontFamily: 'Tajawal',
                            color: _textColor,
                          ),
                          decoration: _buildInputDecoration(
                            'عدد خانات كلمة المرور',
                          ),
                          validator: (value) {
                            if (value == null ||
                                value.isEmpty ||
                                int.tryParse(value) == null ||
                                int.parse(value) <= 0) {
                              return 'يجب إدخال عدد صحيح موجب';
                            }
                            return null;
                          },
                          onChanged:
                              (val) => setState(
                                () =>
                                    _passwordDigitsCount =
                                        int.tryParse(val) ?? 8,
                              ),
                        ),
                    ],
                  ),

                  const SizedBox(height: 16),
                  DropdownButtonFormField<String>(
                    value: _profile,
                    style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
                    items:
                        _availableProfiles
                            .map(
                              (p) => DropdownMenuItem(
                                value: p,
                                child: Text(
                                  p,
                                  style: TextStyle(
                                    fontFamily: 'Tajawal',
                                    color: _textColor,
                                  ),
                                ),
                              ),
                            )
                            .toList(),
                    onChanged: (val) => setState(() => _profile = val),
                    decoration: _buildInputDecoration('اختر البروفايل'),
                    dropdownColor: _cardColor,
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _rowsPerPage,
                          items:
                              List.generate(20, (index) => index + 1)
                                  .map(
                                    (val) => DropdownMenuItem(
                                      value: val,
                                      child: Text(
                                        '$val صفوف',
                                        style: TextStyle(
                                          fontFamily: 'Tajawal',
                                          color: _textColor,
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged: (val) {
                            if (val != null) {
                              setState(() => _rowsPerPage = val);
                            }
                          },
                          decoration: _buildInputDecoration(
                            'عدد الصفوف في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _columnsPerPage,
                          items:
                              [3, 4]
                                  .map(
                                    (val) => DropdownMenuItem(
                                      value: val,
                                      child: Text(
                                        '$val أعمدة',
                                        style: TextStyle(
                                          fontFamily: 'Tajawal',
                                          color: _textColor,
                                        ),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged: (val) {
                            if (val != null) {
                              setState(() => _columnsPerPage = val);
                            }
                          },
                          decoration: _buildInputDecoration(
                            'عدد الأعمدة في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            SwitchListTile(
              title: Text(
                'تقييد حسب أول تسجيل دخول',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: _textColor,
                  fontWeight: FontWeight.w600, // لجعل النص أكثر وضوحًا
                ),
              ),
              subtitle: Text(
                _restrictOnFirstLogin
                    ? 'سيتم تقييد المستخدم باول جهاز يقوم بالتسجيل'
                    : 'لن يتم تقييد المستخدم باول جهاز يقوم بالتسجيل',
                style: TextStyle(
                  fontFamily: 'Tajawal',
                  color: _textColor.withOpacity(0.7),
                  fontSize: 13, // حجم خط أصغر قليلاً للتفاصيل
                ),
              ),
              value: _restrictOnFirstLogin,
              onChanged:
                  (value) => setState(() => _restrictOnFirstLogin = value),
              activeColor: _primaryColor,
              activeTrackColor: _primaryColor.withOpacity(
                0.3,
              ), // إضافة تدرج لوني عصري
              dense: true, // لجعل العنصر أكثر إحكاما
              contentPadding: EdgeInsets.symmetric(
                horizontal: 12,
              ), // تعديل المسافات
            ),

            CheckboxListTile(
              title: Text(
                'إضافة الرقم التسلسلي',
                style: TextStyle(fontFamily: 'Tajawal', color: _textColor),
              ),
              value: _includeSerialNumber,
              onChanged: (value) {
                setState(() => _includeSerialNumber = value!);
              },
              activeColor: _primaryColor,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed:
                  _isLoading
                      ? null
                      : () {
                        _generateUserManagerCards();
                      },
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
              ),
              child: const Text(
                'إنشاء المستخدمين',
                style: TextStyle(fontFamily: 'Tajawal'),
              ),
            ),
            const SizedBox(height: 24),
            _buildDesignCard(context),
          ],
        ),
      ),
    );
  }

  /// بطاقة الإعدادات العامة للنموذج
  Widget _buildCardSettings(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)),
      ),
      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,
        ],
      ),
    );
  }

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

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

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

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

            const Divider(color: Colors.white24),

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

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

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

  /// بطاقة المعاينة والتصميم
  Widget _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(fontFamily: 'Tajawal', color: _textColor),
              ),
              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),
              ),
            ),
            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),
              ),
            ],
            const SizedBox(height: 16),
            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,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

اريد ان يكون الارسال بدلاً من كتابة الرقم اريد ان اقوم باختيارة اختيار سوى في sms او في الوتس اب
ملاحظة اعطيني الجزء السابق والجزء المراد استبدالة بة