لما ظهر يجب منح اذن ادارة التخزين للمتابعة ولم يطلب منح الاذن لاقوم بذلك قبل انشاء الكروت
الكود
import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:open_file/open_file.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:router_os_client/router_os_client.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'dart:io' show Platform;

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

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

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

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

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

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

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

  Future<void> _generateHotspotCards() async {
    // أضف هذا في بداية دالة _generateHotspotCards
    if (_backgroundImage == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('الرجاء اختيار صورة خلفية أولاً'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    final formKey =
        _tabController.index == 0 ? _singleUserFormKey : _multiUserFormKey;
    if (!formKey.currentState!.validate()) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('الرجاء ملء جميع الحقول المطلوبة'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }
    int calculatedLimitBytes =
        _limitBytes > 0 ? _calculateLimitBytes(_limitBytes, _dataUnit) : 0;
    int totalMinutes = _limitHours * 60;
    setState(() {
      _isLoading = true;
      _progress = 0.0;
      _progressMessage = 'بدء إنشاء الكروت...';
      _generatedCards.clear();
      _showCounter = true;
      _successfulCards = 0;
      _failedCards = 0;
    });

    final uniqueUsernames = <String>{};

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

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

        uniqueUsernames.add(generatedUsername);
        return generatedUsername;
      }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      // حساب أبعاد الصورة هنا
      final image = FileImage(file);
      final completer = Completer<ImageInfo>();
      image
          .resolve(ImageConfiguration())
          .addListener(
            ImageStreamListener((info, _) {
              if (!completer.isCompleted) {
                completer.complete(info);
              }
            }),
          );

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

      setState(() {
        _backgroundImage = file;
        _imageBytes = bytes;
        _actualImageWidth = imageWidth;
        _actualImageHeight = imageHeight;
      });
    }
  }

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

    final path = await _pickSavePath();
    if (path == null) 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;
      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: [
                    pw.Positioned(
                      left:
                          _usernamePosition.dx * cardWidth +
                          ((MediaQuery.of(context).size.width < 350)
                              ? MediaQuery.of(context).size.width * 0.080
                              : (MediaQuery.of(context).size.width < 410)
                              ? MediaQuery.of(context).size.width * 0.075
                              : (MediaQuery.of(context).size.width < 450)
                              ? MediaQuery.of(context).size.width * 0.045
                              : (MediaQuery.of(context).size.width < 480)
                              ? MediaQuery.of(context).size.width * 0.01
                              : 0),
                      top: _usernamePosition.dy * cardHeight,
                      child: pw.Text(
                        card['username']!,
                        style: pw.TextStyle(
                          color: PdfColors.black,
                          fontSize: 12,
                          fontWeight: pw.FontWeight.bold,
                        ),
                      ),
                    ),

                    if (card['password']!.isNotEmpty &&
                        _generationType != 'similar_username')
                      pw.Positioned(
                        left:
                            _passwordPosition.dx * cardWidth +
                            ((MediaQuery.of(context).size.width < 350)
                                ? MediaQuery.of(context).size.width * 0.080
                                : (MediaQuery.of(context).size.width < 410)
                                ? MediaQuery.of(context).size.width * 0.075
                                : (MediaQuery.of(context).size.width < 450)
                                ? MediaQuery.of(context).size.width * 0.045
                                : (MediaQuery.of(context).size.width < 480)
                                ? MediaQuery.of(context).size.width * 0.01
                                : 0),
                        top: _passwordPosition.dy * cardHeight,
                        child: pw.Text(
                          card['password']!,
                          style: pw.TextStyle(
                            color: PdfColors.black,
                            fontSize: 12,
                            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 pdfBytes = await pdf.save();
      final file = File(path!);

      // كتابة الملف بشكل متدرج لتجنب مشاكل الذاكرة
      final sink = file.openWrite();
      await sink.addStream(Stream.value(pdfBytes));
      await sink.close();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('تم حفظ الملف في: ${file.path}'),
            duration: Duration(seconds: 5),
          ),
        );
      }

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('تم حفظ ملف PDF بنجاح'),
            backgroundColor: Colors.green,
          ),
        );
        OpenFile.open(path);
      }
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('خطأ في حفظ ملف PDF: $e'),
            backgroundColor: Colors.red,
          ),
        );
        print('$e');
      }
    } finally {
      if (mounted) {
        setState(() => _isLoading = false);
      }
    }
  }

  Future<String?> _pickSavePath() async {
    try {
      // طلب إذن التخزين أولاً (لأندرويد 10+)
      if (Platform.isAndroid) {
        var status = await Permission.storage.status;
        if (!status.isGranted) {
          status = await Permission.storage.request();
          if (!status.isGranted) {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('يجب منح إذن التخزين للمتابعة')),
              );
            }
            return null;
          }
        }

        // لأندرويد 13+ نحتاج إذن إضافي
        if (await Permission.manageExternalStorage.isRestricted) {
          status = await Permission.manageExternalStorage.request();
          if (!status.isGranted) {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('يجب منح إذن إدارة التخزين للمتابعة'),
                ),
              );
            }
            return null;
          }
        }
      }

      // طلب من المستخدم اختيار مجلد
      final outputDir = await FilePicker.platform.getDirectoryPath(
        dialogTitle: 'اختر المجلد لحفظ ملف PDF',
      );

      if (outputDir == null) {
        if (mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('لم يتم اختيار مجلد للحفظ')),
          );
        }
        return null;
      }

      // إنشاء اسم الملف
      final now = DateTime.now();
      final fileName = 'كروت_الهوتسبوت_${now.year}-${now.month}-${now.day}.pdf';

      // دمج المسار
      final fullPath = p.join(outputDir, fileName);

      return fullPath;
    } catch (e) {
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('حدث خطأ أثناء اختيار مسار الحفظ: $e')),
        );
      }
      return null;
    }
  }

  @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: [
          Container(
            width: 280,
            decoration: BoxDecoration(
              color: Colors.white.withOpacity(0.05),
              border: Border(
                right: BorderSide(color: Colors.white.withOpacity(0.1)),
              ),
            ),
            child: Column(
              children: [
                const SizedBox(height: 40),
                Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  child: Row(
                    children: [
                      Icon(Icons.credit_card, color: _primaryColor, size: 28),
                      const SizedBox(width: 10),
                      Text(
                        'إنشاء كروت هوتسبوت',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 30),
                _buildDesktopNavigation(),
              ],
            ),
          ),
          Expanded(
            child: Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                  colors: [
                    _backgroundColor.withOpacity(0.9),
                    _backgroundColor.withOpacity(0.7),
                  ],
                ),
              ),
              child: Column(
                children: [
                  Container(
                    height: 60,
                    color: Colors.white.withOpacity(0.05),
                    child: TabBar(
                      controller: _tabController,
                      indicatorColor: _primaryColor,
                      indicatorWeight: 3,
                      labelColor: _primaryColor,
                      unselectedLabelColor: Colors.white.withOpacity(0.5),
                      tabs: const [
                        Tab(icon: Icon(Icons.person_add), text: 'مستخدم واحد'),
                        Tab(
                          icon: Icon(Icons.group_add),
                          text: 'مجموعة مستخدمين',
                        ),
                      ],
                    ),
                  ),
                  Expanded(
                    child: Stack(
                      children: [
                        TabBarView(
                          controller: _tabController,
                          children: [
                            _buildSingleCardTab(),
                            _buildMultipleCardsTab(),
                          ],
                        ),
                        if (_isLoading) _buildLoadingOverlay(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDesktopNavigation() {
    return Column(
      children: [
        _buildNavItem(
          icon: Icons.person_add,
          title: 'مستخدم واحد',
          isActive: _tabController.index == 0,
          onTap: () => setState(() => _tabController.index = 0),
        ),
        _buildNavItem(
          icon: Icons.group_add,
          title: 'مجموعة مستخدمين',
          isActive: _tabController.index == 1,
          onTap: () => setState(() => _tabController.index = 1),
        ),
        const SizedBox(height: 20),
        const Divider(color: Colors.white24, height: 1),
        const SizedBox(height: 20),
        _buildNavItem(
          icon: Icons.settings,
          title: 'الإعدادات',
          isActive: false,
          onTap: () {},
        ),
        _buildNavItem(
          icon: Icons.help_outline,
          title: 'المساعدة',
          isActive: false,
          onTap: () {},
        ),
      ],
    );
  }

  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: 16),
        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(
                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 _buildMobileLayout(BuildContext context) {
    return Scaffold(
      backgroundColor: _backgroundColor,
      appBar: AppBar(
        title: Text(
          'إنشاء كروت هوتسبوت',
          style: TextStyle(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: 'مجموعة مستخدمين'),
          ],
        ),
      ),
      body: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  _backgroundColor.withOpacity(0.9),
                  _backgroundColor.withOpacity(0.7),
                ],
              ),
            ),
            child: TabBarView(
              controller: _tabController,
              children: [_buildSingleCardTab(), _buildMultipleCardsTab()],
            ),
          ),
          if (_isLoading) _buildLoadingOverlay(),
        ],
      ),
    );
  }

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

  Widget _buildMultipleCardsTab() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Form(
        key: _multiUserFormKey,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildSettingsCard(
              'إعدادات مجموعة الكروت',
              Column(
                children: [
                  _buildCommonFormFields(),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _rowsPerPage,
                          items:
                              List.generate(20, (index) => index + 1)
                                  .map(
                                    (value) => DropdownMenuItem<int>(
                                      value: value,
                                      child: Text(
                                        '$value صفوف',
                                        style: TextStyle(color: _textColor),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged:
                              (value) => setState(() => _rowsPerPage = value!),
                          decoration: _buildInputDecoration(
                            'عدد الصفوف في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                          style: TextStyle(color: _textColor),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: DropdownButtonFormField<int>(
                          value: _columnsPerPage,
                          items:
                              [3, 4]
                                  .map(
                                    (value) => DropdownMenuItem<int>(
                                      value: value,
                                      child: Text(
                                        '$value أعمدة',
                                        style: TextStyle(color: _textColor),
                                      ),
                                    ),
                                  )
                                  .toList(),
                          onChanged:
                              (value) =>
                                  setState(() => _columnsPerPage = value!),
                          decoration: _buildInputDecoration(
                            'عدد الأعمدة في الصفحة',
                          ),
                          dropdownColor: _cardColor,
                          style: TextStyle(color: _textColor),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed:
                  _isLoading ||
                          (_tabController.index == 0 &&
                              !_singleUserFormKey.currentState!.validate()) ||
                          (_tabController.index == 1 &&
                              !_multiUserFormKey.currentState!.validate()) ||
                          _backgroundImage == null
                      ? null
                      : _generateHotspotCards,
              style: ElevatedButton.styleFrom(
                backgroundColor:
                    _isLoading ||
                            (_tabController.index == 0 &&
                                !_singleUserFormKey.currentState!.validate()) ||
                            (_tabController.index == 1 &&
                                !_multiUserFormKey.currentState!.validate()) ||
                            _backgroundImage == null
                        ? _primaryColor.withOpacity(0.5)
                        : _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
                elevation: 3,
                shadowColor: _primaryColor.withOpacity(0.3),
              ),
              child: const Text('إنشاء الكروت'),
            ),
            const SizedBox(height: 24),
            _buildDesignCard(),
          ],
        ),
      ),
    );
  }

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

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

  Widget _buildCommonFormFields() {
    return Column(
      children: [
        TextFormField(
          initialValue: _numberOfCards.toString(),
          keyboardType: TextInputType.number,
          decoration: _buildInputDecoration('عدد الكروت المراد إنشاؤها'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null ||
                value.isEmpty ||
                int.tryParse(value) == null ||
                int.parse(value) <= 0) {
              return 'يجب إدخال عدد صحيح موجب';
            }
            return null;
          },
          onChanged:
              (value) =>
                  setState(() => _numberOfCards = int.tryParse(value) ?? 1),
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _generationType,
          items: const [
            DropdownMenuItem(
              value: 'username_only',
              child: Text('اسم مستخدم فقط'),
            ),
            DropdownMenuItem(
              value: 'similar_username',
              child: Text('اسم مستخدم وكلمة سر متشابهين'),
            ),
            DropdownMenuItem(
              value: 'unique_credentials',
              child: Text('اسم مستخدم وكلمة سر مختلفين'),
            ),
          ],
          onChanged: (value) => setState(() => _generationType = value!),
          decoration: _buildInputDecoration('نوع التوليد'),
          dropdownColor: _cardColor,
          style: TextStyle(color: _textColor),
        ),
        const SizedBox(height: 16),
        Row(
          children: [
            Expanded(
              child: TextFormField(
                initialValue: _usernameDigitsCount.toString(),
                keyboardType: TextInputType.number,
                decoration: _buildInputDecoration('عدد خانات اسم المستخدم'),
                style: TextStyle(color: _textColor),
                validator: (value) {
                  if (value == null ||
                      value.isEmpty ||
                      int.tryParse(value) == null ||
                      int.parse(value) <= 0) {
                    return 'يجب إدخال عدد صحيح موجب';
                  }
                  return null;
                },
                onChanged:
                    (value) => setState(
                      () => _usernameDigitsCount = int.tryParse(value) ?? 7,
                    ),
              ),
            ),
            if (_generationType == 'unique_credentials') SizedBox(width: 16),
            if (_generationType == 'unique_credentials')
              Expanded(
                child: TextFormField(
                  initialValue: _passwordDigitsCount.toString(),
                  keyboardType: TextInputType.number,
                  decoration: _buildInputDecoration('عدد خانات كلمة المرور'),
                  style: TextStyle(color: _textColor),
                  validator: (value) {
                    if (value == null ||
                        value.isEmpty ||
                        int.tryParse(value) == null ||
                        int.parse(value) <= 0) {
                      return 'يجب إدخال عدد صحيح موجب';
                    }
                    return null;
                  },
                  onChanged:
                      (value) => setState(
                        () => _passwordDigitsCount = int.tryParse(value) ?? 8,
                      ),
                ),
              ),
          ],
        ),
        const SizedBox(height: 16),
        DropdownButtonFormField<String>(
          value: _profile,
          items:
              _availableProfiles
                  .map(
                    (profile) => DropdownMenuItem(
                      value: profile,
                      child: Text(profile, style: TextStyle(color: _textColor)),
                    ),
                  )
                  .toList(),
          onChanged: (value) => setState(() => _profile = value!),
          decoration: _buildInputDecoration('بروفايل الهوتسبوت'),
          dropdownColor: _cardColor,
          style: TextStyle(color: _textColor),
        ),
        const SizedBox(height: 16),
        TextFormField(
          initialValue: _usernamePrefix,
          maxLength: 2,
          decoration: _buildInputDecoration('بادئة اسم المستخدم (1-2 أحرف)'),
          style: TextStyle(color: _textColor),
          validator: (value) {
            if (value == null || value.isEmpty) return 'يجب إدخال بادئة';
            return null;
          },
          onChanged: (value) => setState(() => _usernamePrefix = value),
        ),
        const SizedBox(height: 16),

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

  Widget _buildDesignCard() {
    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(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: _textColor,
              ),
            ),
            const SizedBox(height: 16),
            ElevatedButton.icon(
              onPressed: _pickBackgroundImage,
              icon: Icon(Icons.image, color: _textColor),
              label: Text(
                'اختر صورة خلفية',
                style: TextStyle(color: _textColor),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: _primaryColor,
                foregroundColor: _textColor,
                padding: const EdgeInsets.symmetric(vertical: 12),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
                minimumSize: const Size(double.infinity, 50),
                elevation: 3,
                shadowColor: _primaryColor.withOpacity(0.3),
              ),
            ),
            const SizedBox(height: 16),
            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: [
                  // تحريك اسم المستخدم
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.arrow_upward, color: _textColor),
                        onPressed:
                            () => setState(() {
                              _usernamePosition = Offset(
                                _usernamePosition.dx,
                                (_usernamePosition.dy - 0.01).clamp(0.0, 1.0),
                              );
                            }),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.arrow_back, color: _textColor),
                        onPressed:
                            () => setState(() {
                              _usernamePosition = Offset(
                                (_usernamePosition.dx - 0.01).clamp(0.0, 1.0),
                                _usernamePosition.dy,
                              );
                            }),
                      ),
                      SizedBox(width: 40),
                      IconButton(
                        icon: Icon(Icons.arrow_forward, color: _textColor),
                        onPressed:
                            () => setState(() {
                              _usernamePosition = Offset(
                                (_usernamePosition.dx + 0.01).clamp(0.0, 1.0),
                                _usernamePosition.dy,
                              );
                            }),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      IconButton(
                        icon: Icon(Icons.arrow_downward, color: _textColor),
                        onPressed:
                            () => setState(() {
                              _usernamePosition = Offset(
                                _usernamePosition.dx,
                                (_usernamePosition.dy + 0.01).clamp(0.0, 1.0),
                              );
                            }),
                      ),
                    ],
                  ),
                  // معاينة الكرت
                  Listener(
                    onPointerDown: (details) {
                      final box = context.findRenderObject() as RenderBox;
                      final localPosition = box.globalToLocal(details.position);
                      final imageOffsetX =
                          (_previewCardWidth - _actualImageWidth) / 2;
                      final imageOffsetY =
                          (_previewCardHeight - _actualImageHeight) / 2;
                      final imageLocalX = (localPosition.dx - imageOffsetX)
                          .clamp(0, _actualImageWidth);
                      final imageLocalY = (localPosition.dy - imageOffsetY)
                          .clamp(0, _actualImageHeight);
                      final usernameRect = Rect.fromCenter(
                        center: Offset(
                          _usernamePosition.dx * _actualImageWidth,
                          _usernamePosition.dy * _actualImageHeight,
                        ),
                        width: 100,
                        height: 30,
                      );
                      final passwordRect = Rect.fromCenter(
                        center: Offset(
                          _passwordPosition.dx * _actualImageWidth,
                          _passwordPosition.dy * _actualImageHeight,
                        ),
                        width: 100,
                        height: 30,
                      );
                      setState(() {
                        _isDraggingUsername = usernameRect.contains(
                          Offset(
                            imageLocalX.toDouble(),
                            imageLocalY.toDouble(),
                          ),
                        );
                        _isDraggingPassword =
                            passwordRect.contains(
                              Offset(
                                imageLocalX.toDouble(),
                                imageLocalY.toDouble(),
                              ),
                            ) &&
                            _generationType != 'username_only';
                      });
                    },
                    child: GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onPanUpdate: (details) {
                        final box = context.findRenderObject() as RenderBox;
                        final localPosition = box.globalToLocal(
                          details.globalPosition,
                        );
                        final imageOffsetX =
                            (_previewCardWidth - _actualImageWidth) / 2;
                        final imageOffsetY =
                            (_previewCardHeight - _actualImageHeight) / 2;
                        double imageX =
                            ((localPosition.dx - imageOffsetX).clamp(
                                  0,
                                  _actualImageWidth,
                                ) /
                                _actualImageWidth);
                        double imageY =
                            ((localPosition.dy - imageOffsetY).clamp(
                                  0,
                                  _actualImageHeight,
                                ) /
                                _actualImageHeight);
                        setState(() {
                          if (_isDraggingUsername) {
                            _usernamePosition = Offset(imageX, imageY);
                          } else if (_isDraggingPassword) {
                            _passwordPosition = Offset(imageX, imageY);
                          }
                        });
                      },
                      onPanEnd:
                          (_) => setState(() {
                            _isDraggingUsername = false;
                            _isDraggingPassword = false;
                          }),
                      child: Container(
                        width: _previewCardWidth,
                        height: _previewCardHeight,
                        decoration:
                            _backgroundImage != null
                                ? BoxDecoration(
                                  borderRadius: BorderRadius.circular(8),
                                  image: DecorationImage(
                                    image: FileImage(_backgroundImage!),
                                    fit: BoxFit.contain,
                                  ),
                                )
                                : BoxDecoration(
                                  color: _textColor.withOpacity(0.1),
                                  borderRadius: BorderRadius.circular(8),
                                  border: Border.all(
                                    color: _textColor.withOpacity(0.3),
                                  ),
                                ),
                        child: Stack(
                          children: [
                            if (_backgroundImage == null)
                              Center(
                                child: Text(
                                  'لا توجد صورة خلفية',
                                  style: TextStyle(
                                    color: _textColor.withOpacity(0.5),
                                  ),
                                ),
                              ),
                            Positioned(
                              left:
                                  _usernamePosition.dx * _actualImageWidth +
                                  (_previewCardWidth - _actualImageWidth) / 2,
                              top:
                                  _usernamePosition.dy * _actualImageHeight +
                                  (_previewCardHeight - _actualImageHeight) / 2,
                              child: Text(
                                _tabController.index == 0
                                    ? _username
                                    : 'رمز الدخول',
                                style: const TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                            if (_generationType != 'username_only')
                              Positioned(
                                left:
                                    _passwordPosition.dx * _actualImageWidth +
                                    (_previewCardWidth - _actualImageWidth) / 2,
                                top:
                                    _passwordPosition.dy * _actualImageHeight +
                                    (_previewCardHeight - _actualImageHeight) /
                                        2,
                                child: Text(
                                  'كلمة السر',
                                  style: const TextStyle(
                                    color: Colors.black,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            if (_isDraggingUsername || _isDraggingPassword)
                              Positioned.fill(
                                child: Align(
                                  alignment: Alignment.center,
                                  child: Icon(
                                    Icons.open_with,
                                    color: Colors.white,
                                    size: 40,
                                  ),
                                ),
                              ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  if (_generationType != 'username_only') ...[
                    const SizedBox(height: 16),
                    Text(
                      'تحريك كلمة السر:',
                      style: TextStyle(color: _textColor),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                          icon: Icon(Icons.arrow_upward, color: _textColor),
                          onPressed:
                              () => setState(() {
                                _passwordPosition = Offset(
                                  _passwordPosition.dx,
                                  (_passwordPosition.dy - 0.01).clamp(0.0, 1.0),
                                );
                              }),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                          icon: Icon(Icons.arrow_back, color: _textColor),
                          onPressed:
                              () => setState(() {
                                _passwordPosition = Offset(
                                  (_passwordPosition.dx - 0.01).clamp(0.0, 1.0),
                                  _passwordPosition.dy,
                                );
                              }),
                        ),
                        SizedBox(width: 40),
                        IconButton(
                          icon: Icon(Icons.arrow_forward, color: _textColor),
                          onPressed:
                              () => setState(() {
                                _passwordPosition = Offset(
                                  (_passwordPosition.dx + 0.01).clamp(0.0, 1.0),
                                  _passwordPosition.dy,
                                );
                              }),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        IconButton(
                          icon: Icon(Icons.arrow_downward, color: _textColor),
                          onPressed:
                              () => setState(() {
                                _passwordPosition = Offset(
                                  _passwordPosition.dx,
                                  (_passwordPosition.dy + 0.01).clamp(0.0, 1.0),
                                );
                              }),
                        ),
                      ],
                    ),
                  ],
                  const SizedBox(height: 8),
                  Text(
                    'يمكنك تحريك العناصر إما بالسحب والإفلات أو باستخدام الأزرار',
                    style: TextStyle(color: Colors.white.withOpacity(0.7)),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

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

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