قم باضافة ميزة singlechildview للكود دون التاثير علية او على عملة
// main.dart
import 'dart:async';
import 'dart:convert';
import 'package:excel/excel.dart' as excel;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:intl/intl.dart' as intl;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sms_checker/splash.dart';
import 'package:telephony/telephony.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:file_picker/file_picker.dart';

// مكتبة الاتصال التلقائي
import 'package:flutter_phone_direct_caller/flutter_phone_direct_caller.dart';

// استيراد شاشة الترحيب المنفصلة
import 'welcome_screen.dart';

const tajawalFont = 'Tajawal';

void main() => runApp(const SMSApp());

void onBackgroundMessage(SmsMessage message) {
  debugPrint("رسالة واردة في الخلفية: ${message.body}");
}

final ColorScheme lightColorScheme = ColorScheme(
  primary: const Color(0xFFEF6C00), // برتقالي قوي وأمتع للعين
  onPrimary: Colors.white,
  primaryContainer: const Color(0xFFFFE0B2), // برتقالي فاتح للخلفيات
  onPrimaryContainer: const Color(0xFF3E2723),

  secondary: const Color(0xFF8D6E63), // بُني معتدل دافئ
  onSecondary: Colors.white,
  secondaryContainer: const Color(0xFFD7CCC8),
  onSecondaryContainer: const Color(0xFF3E2723),

  tertiary: const Color(0xFF455A64), // رمادي مزرق بارد وهادئ
  onTertiary: Colors.white,
  tertiaryContainer: const Color(0xFFCFD8DC), // أزرق فاتح مريح للنظر
  onTertiaryContainer: const Color(0xFF263238),

  error: const Color(0xFFD32F2F), // أحمر واضح وجذاب
  onError: Colors.white,
  errorContainer: const Color(0xFFFFCDD2),
  onErrorContainer: const Color(0xFFB71C1C),

  background: const Color(0xFFFFF8E1), // بيج ناعم دافئ أكثر راحة
  onBackground: const Color(0xFF37474F), // رمادي غامق للنصوص
  surface: Colors.white,
  onSurface: const Color(0xFF37474F),

  surfaceVariant: const Color(0xFFFFF3E0), // خلفية دافئة ناعمة

  onSurfaceVariant: const Color(0xFF6D4C41),
  outline: const Color(0xFFBCAAA4), // توسعة للألوان البنية الفاتحة لحدود لطيفة

  shadow: Colors.black45,
  inverseSurface: const Color(0xFFBF360C),
  onInverseSurface: const Color(0xFFFFF3E0),
  inversePrimary: const Color(0xFFFFB300),
  brightness: Brightness.light,
);

class SMSApp extends StatelessWidget {
  const SMSApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'حوّلها',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: lightColorScheme,
        fontFamily: tajawalFont,
        useMaterial3: true,
        appBarTheme: AppBarTheme(
          backgroundColor: Colors.transparent,
          foregroundColor: lightColorScheme.onPrimary,
          elevation: 6,
          centerTitle: true,
          titleTextStyle: const TextStyle(
            fontSize: 22,
            fontWeight: FontWeight.w700,
            letterSpacing: 0.6,
            fontFamily: tajawalFont,
          ),
          iconTheme: IconThemeData(color: lightColorScheme.onPrimary, size: 28),
          toolbarHeight: 100,
          shadowColor: lightColorScheme.primary.withOpacity(0.5),
        ),
        cardTheme: CardTheme(
          color: lightColorScheme.surface,
          elevation: 3,
          margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          surfaceTintColor: Colors.transparent,
        ),
        elevatedButtonTheme: ElevatedButtonThemeData(
          style: ElevatedButton.styleFrom(
            backgroundColor: lightColorScheme.primary,
            foregroundColor: lightColorScheme.onPrimary,
            padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 24),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            elevation: 3,
            textStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              fontFamily: tajawalFont,
            ),
          ),
        ),
        outlinedButtonTheme: OutlinedButtonThemeData(
          style: OutlinedButton.styleFrom(
            foregroundColor: lightColorScheme.primary,
            side: BorderSide(color: lightColorScheme.primary, width: 2),
            padding: const EdgeInsets.symmetric(vertical: 14, horizontal: 24),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            textStyle: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w700,
              fontFamily: tajawalFont,
            ),
          ),
        ),
        textButtonTheme: TextButtonThemeData(
          style: TextButton.styleFrom(
            foregroundColor: lightColorScheme.primary,
            textStyle: const TextStyle(
              fontWeight: FontWeight.w800,
              fontSize: 16,
              fontFamily: tajawalFont,
            ),
          ),
        ),
        snackBarTheme: SnackBarThemeData(
          behavior: SnackBarBehavior.floating,
          backgroundColor: lightColorScheme.primary,
          elevation: 5,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          contentTextStyle: TextStyle(
            color: lightColorScheme.onPrimary,
            fontWeight: FontWeight.w600,
            fontSize: 15,
            fontFamily: tajawalFont,
          ),
          actionTextColor: lightColorScheme.onPrimaryContainer,
        ),
        inputDecorationTheme: InputDecorationTheme(
          filled: true,
          fillColor: lightColorScheme.surfaceVariant.withOpacity(0.3),
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 18,
            vertical: 16,
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: BorderSide.none,
          ),
          focusedBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: BorderSide(color: lightColorScheme.primary, width: 2.5),
          ),
          errorBorder: OutlineInputBorder(
            borderRadius: BorderRadius.circular(16),
            borderSide: BorderSide(color: lightColorScheme.error, width: 2),
          ),
          labelStyle: TextStyle(
            color: lightColorScheme.onSurfaceVariant,
            fontWeight: FontWeight.w600,
            fontFamily: tajawalFont,
            fontSize: 15,
          ),
          hintStyle: TextStyle(
            color: lightColorScheme.onSurfaceVariant.withOpacity(0.7),
            fontFamily: tajawalFont,
            fontSize: 14,
          ),
          prefixIconColor: lightColorScheme.primary,
        ),
        dialogTheme: DialogTheme(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(24),
          ),
          elevation: 8,
          backgroundColor: lightColorScheme.surface,
          contentTextStyle: TextStyle(
            color: lightColorScheme.onSurface,
            fontSize: 16,
            fontFamily: tajawalFont,
          ),
          titleTextStyle: TextStyle(
            fontWeight: FontWeight.bold,
            fontSize: 20,
            color: lightColorScheme.primary,
            fontFamily: tajawalFont,
          ),
        ),
        listTileTheme: ListTileThemeData(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 20,
            vertical: 10,
          ),
          iconColor: lightColorScheme.primary,
          textColor: lightColorScheme.onSurface,
          dense: true,
          style: ListTileStyle.list,
        ),
        chipTheme: ChipThemeData(
          backgroundColor: lightColorScheme.primaryContainer,
          selectedColor: lightColorScheme.primary,
          secondarySelectedColor: lightColorScheme.primary.withOpacity(0.8),
          disabledColor: lightColorScheme.surfaceVariant.withOpacity(0.5),
          labelStyle: const TextStyle(
            fontFamily: tajawalFont,
            fontWeight: FontWeight.w700,
            color: Colors.white,
          ),
          secondaryLabelStyle: TextStyle(color: lightColorScheme.onPrimary),
          padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          brightness: Brightness.light,
          side: BorderSide.none,
        ),
        dividerTheme: DividerThemeData(
          color: lightColorScheme.outline.withOpacity(0.3),
          thickness: 1,
          space: 0,
        ),
        progressIndicatorTheme: ProgressIndicatorThemeData(
          color: lightColorScheme.primary,
          linearTrackColor: lightColorScheme.primaryContainer.withOpacity(0.5),
        ),
        bottomSheetTheme: BottomSheetThemeData(
          backgroundColor: lightColorScheme.surface,
          shape: const RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
          ),
          elevation: 8,
        ),
      ),
      home: ModernSplashScreen(),
      routes: {'/home': (context) => const SMSHomePage()},
    );
  }
}

class ThousandsSeparatorInputFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
    TextEditingValue oldValue,
    TextEditingValue newValue,
  ) {
    String onlyDigits = newValue.text.replaceAll(RegExp(r'[^0-9]'), '');
    if (onlyDigits.isEmpty) return newValue.copyWith(text: '');

    final buffer = StringBuffer();
    int len = onlyDigits.length;
    for (int i = 0; i < len; i++) {
      buffer.write(onlyDigits[i]);
      int posFromRight = len - i - 1;
      if (posFromRight % 3 == 0 && i != len - 1) buffer.write(',');
    }

    return TextEditingValue(
      text: buffer.toString(),
      selection: TextSelection.collapsed(offset: buffer.length),
    );
  }
}

class TransferItem {
  String number;
  int amount;
  String? pin;

  TransferItem({required this.number, required this.amount, this.pin});

  Map<String, dynamic> toMap() {
    return {'number': number, 'amount': amount, 'pin': pin};
  }

  factory TransferItem.fromMap(Map<String, dynamic> map) {
    return TransferItem(
      number: map['number'],
      amount: map['amount'],
      pin: map['pin'],
    );
  }
}

extension ContactExtensions on Contact {
  String initials() {
    if (displayName.isEmpty) return '';

    final parts = displayName.trim().split(RegExp(r'\s+'));
    if (parts.length == 1) {
      return parts[0].substring(0, 1).toUpperCase();
    } else {
      return (parts[0].substring(0, 1) + parts[1].substring(0, 1))
          .toUpperCase();
    }
  }
}

class NumberAmount {
  String number;
  String? displayName;
  int amount;

  NumberAmount({required this.number, this.displayName, required this.amount});
}

class SMSHomePage extends StatefulWidget {
  const SMSHomePage({super.key});

  @override
  _SMSHomePageState createState() => _SMSHomePageState();
}

class _SMSHomePageState extends State<SMSHomePage>
    with WidgetsBindingObserver, TickerProviderStateMixin {
  final Telephony _telephony = Telephony.instance;
  SharedPreferences? _prefs;

  Map<String, bool> _amountEdited = {};

  List<TransferItem> _transferList = [];
  String _selectedMethod = 'yemenMobile';
  bool _isTransferring = false;
  bool _stopTransferRequested = false;

  List<Map<String, dynamic>> _transferLogs = [];
  List<String> _savedNumbers = [];
  List<int> _savedAmounts = [];
  bool _didShowFavoritesDialog = false;
  String? _selectedQuickNumber;
  int _currentBalance = 0;

  late AnimationController _fabAnimationController;
  late Animation<double> _fabAnimation;

  Widget _buildAppBarActionButton({
    required IconData icon,
    required String tooltip,
    required VoidCallback onPressed,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4),
      child: Tooltip(
        message: tooltip,
        child: IconButton(
          icon: Icon(icon, color: Colors.white),
          onPressed: onPressed,
          style: IconButton.styleFrom(
            backgroundColor: Colors.white.withOpacity(0.15),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            padding: const EdgeInsets.all(
              8,
            ), // استخدم padding أقل (8 بدل 10 مثلا)
          ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initApp();
    _loadContactsOnce();

    _fabAnimationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 400),
    );
    _fabAnimation = CurvedAnimation(
      parent: _fabAnimationController,
      curve: Curves.easeInOutBack,
    );

    // لضمان ظهور زر التحويل دائماً
    _fabAnimationController.value = 1;
  }

  void _showBalanceDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          insetPadding: const EdgeInsets.all(24),
          child: Container(
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surface,
              borderRadius: BorderRadius.circular(24),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.2),
                  blurRadius: 16,
                  spreadRadius: 2,
                ),
              ],
            ),
            padding: const EdgeInsets.all(24),
            child: Directionality(
              textDirection: TextDirection.rtl,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  // Header with icon and title
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Theme.of(
                        context,
                      ).colorScheme.primary.withOpacity(0.1),
                      shape: BoxShape.circle,
                    ),
                    child: Icon(
                      Icons.account_balance_wallet_rounded,
                      size: 36,
                      color: Theme.of(context).colorScheme.primary,
                    ),
                  ),
                  const SizedBox(height: 16),

                  // Title
                  Text(
                    'الرصيد الحالي',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                      fontFamily: tajawalFont,
                      color: Theme.of(
                        context,
                      ).colorScheme.onSurface.withOpacity(0.8),
                    ),
                  ),
                  const SizedBox(height: 16),

                  // Balance amount
                  TweenAnimationBuilder(
                    duration: const Duration(milliseconds: 800),
                    tween: Tween<double>(
                      begin: 0,
                      end: _currentBalance.toDouble(),
                    ),
                    builder: (context, value, child) {
                      return Text(
                        '${_formatWithThousandsSeparator(value.toInt())} ريال',
                        style: TextStyle(
                          fontSize: 28,
                          fontWeight: FontWeight.bold,
                          fontFamily: tajawalFont,
                          color: Theme.of(context).colorScheme.primary,
                          height: 1.2,
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 24),

                  // Close button
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        foregroundColor: Colors.white,
                        backgroundColor: Theme.of(context).colorScheme.primary,
                        padding: const EdgeInsets.symmetric(vertical: 14),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                        elevation: 0, // ← تم تصحيح مكانها هنا
                        shadowColor: Colors.transparent,
                      ),
                      child: const Text(
                        'إغلاق',
                        style: TextStyle(
                          fontFamily: tajawalFont,
                          fontSize: 16,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  String convertNumberToArabicWords(int number) {
    if (number == 0) return "صفر";

    final ones = [
      "",
      "واحد",
      "اثنان",
      "ثلاثة",
      "أربعة",
      "خمسة",
      "ستة",
      "سبعة",
      "ثمانية",
      "تسعة",
      "عشرة",
      "أحد عشر",
      "اثنا عشر",
      "ثلاثة عشر",
      "أربعة عشر",
      "خمسة عشر",
      "ستة عشر",
      "سبعة عشر",
      "ثمانية عشر",
      "تسعة عشر",
    ];

    final tens = [
      "",
      "",
      "عشرون",
      "ثلاثون",
      "أربعون",
      "خمسون",
      "ستون",
      "سبعون",
      "ثمانون",
      "تسعون",
    ];

    final hundreds = [
      "",
      "مئة",
      "مئتان",
      "ثلاثمئة",
      "أربعمئة",
      "خمسمئة",
      "ستمئة",
      "سبعمئة",
      "ثمانمئة",
      "تسعمئة",
    ];

    String threeDigitsToWords(int n) {
      if (n == 0) return "";

      String words = "";

      int h = n ~/ 100;
      int rem = n % 100;

      if (h > 0) {
        words += hundreds[h];
      }

      if (rem > 0) {
        if (rem < 20) {
          if (words.isNotEmpty) words += " و ";
          words += ones[rem];
        } else {
          int t = rem ~/ 10;
          int o = rem % 10;
          if (o > 0) {
            if (words.isNotEmpty) words += " و ";
            words += ones[o];
            words += " و ";
            words += tens[t];
          } else {
            if (words.isNotEmpty) words += " و ";
            words += tens[t];
          }
        }
      }
      return words;
    }

    List<int> parts = [];
    int num = number;

    while (num > 0) {
      parts.add(num % 1000);
      num ~/= 1000;
    }

    List<String> partsWords = [];

    for (int i = 0; i < parts.length; i++) {
      int part = parts[i];
      if (part == 0) continue;

      String partWord = threeDigitsToWords(part);

      if (i == 1) {
        // ألف
        if (part == 1) {
          partWord = "ألف";
        } else if (part == 2) {
          partWord = "ألفان";
        } else if (part >= 3 && part <= 10) {
          partWord += " آلاف";
        } else {
          partWord += " ألف";
        }
      } else if (i == 2) {
        // مليون
        if (part == 1) {
          partWord = "مليون";
        } else if (part == 2) {
          partWord = "مليونان";
        } else if (part >= 3 && part <= 10) {
          partWord += " ملايين";
        } else {
          partWord += " مليون";
        }
      }

      partsWords.insert(0, partWord);
    }

    return partsWords.join(" و ");
  }

  Future<int> _loadCurrentBalanceFromJsonData() async {
    final prefs = await SharedPreferences.getInstance();
    final savedData = prefs.getString('balance_data');
    if (savedData != null) {
      final Map<String, dynamic> jsonData = jsonDecode(savedData);
      return jsonData['current_balance'] ?? 0;
    }
    return 0;
  }

  Future<bool> requestStoragePermission() async {
    if (Platform.isAndroid) {
      var status = await Permission.storage.status;
      if (!status.isGranted) {
        status = await Permission.storage.request();
        if (!status.isGranted) {
          return false;
        }
      }
    }
    return true;
  }

  // تخزين الأسماء في متغير
  Map<String, String?> _numberToContactName = {};
  Future<void> _exportTransferLogsToCsv() async {
    if (_transferLogs.isEmpty) {
      _showSnackBar('لا يوجد سجل تصدير');
      return;
    }

    // بناء محتوى CSV
    final headers = [
      'رقم الهاتف',
      'المبلغ',
      'الحالة',
      'طريقة التحويل',
      'التاريخ',
    ];

    String csvContent = headers.join(',') + '\n';

    for (var log in _transferLogs) {
      List<String> row = [
        '"${log['number'] ?? ''}"',
        '"${log['amount'] ?? ''}"',
        '"${(log['success'] == true) ? 'ناجحة' : 'فاشلة'}"',
        '"${_getMethodName((log['method'] ?? '').toString())}"',
        '"${log['timestamp'] ?? ''}"',
      ];

      csvContent += row.join(',') + '\n';
    }

    // طلب تحديد المجلد من المستخدم
    String? selectedDirectory = await FilePicker.platform.getDirectoryPath();

    if (selectedDirectory == null) {
      _showSnackBar('تم إلغاء اختيار المسار');
      return; // المستخدم ألغى اختيار المجلد
    }

    // اسم الملف
    String fileName =
        'سجل عمليات تحويل ${intl.DateFormat('yyyy-MM-dd').format(DateTime.now())}.csv';
    String filePath = '$selectedDirectory/$fileName';

    try {
      final file = File(filePath);
      final bom = '\uFEFF'; // إضافة BOM لترميز UTF-8
      await file.writeAsString(bom + csvContent, encoding: utf8);
      _showSnackBar('تم تصدير السجل إلى:\n$filePath');
    } catch (e) {
      _showSnackBar('خطأ أثناء حفظ الملف: $e');
    }
  }

  Future<bool> _showDeleteConfirmation(BuildContext context) async {
    return await showDialog<bool>(
          context: context,
          builder:
              (context) => AlertDialog(
                title: Text(
                  'تأكيد الحذف',
                  style: TextStyle(fontFamily: tajawalFont),
                ),
                content: Text(
                  'هل أنت متأكد من رغبتك في حذف هذا العنصر؟',
                  style: TextStyle(fontFamily: tajawalFont),
                ),
                actions: [
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(false),
                    child: Text(
                      'إلغاء',
                      style: TextStyle(fontFamily: tajawalFont),
                    ),
                  ),
                  TextButton(
                    onPressed: () => Navigator.of(context).pop(true),
                    child: Text(
                      'حذف',
                      style: TextStyle(
                        fontFamily: tajawalFont,
                        color: Theme.of(context).colorScheme.error,
                      ),
                    ),
                  ),
                ],
              ),
        ) ??
        false;
  }

  Future<void> _confirmAndRemove(int index, BuildContext context) async {
    final shouldDelete = await _showDeleteConfirmation(context);
    if (shouldDelete == true) {
      _removeTransferAt(index);
    }
  }

  // دالة تحميل الأسماء للجهات الاتصال
  Future<void> _loadContactsOnce() async {
    if (!await Permission.contacts.isGranted) {
      await Permission.contacts.request();
    }
    if (!mounted) return;

    final contacts = await FlutterContacts.getContacts(withProperties: true);

    final map = <String, String?>{};
    for (var contact in contacts) {
      for (var phone in contact.phones) {
        final normalizedPhone = normalizeYemenPhoneNumber(phone.number);
        map[normalizedPhone] = contact.displayName;
      }
    }

    setState(() {
      _numberToContactName = map;
    });
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _fabAnimationController.dispose();
    super.dispose();
  }

  Future<void> _showPinManagementDialog() async {
    // نحفظ أرقام السرية لكل طريقة في SharedPreferences باستخدام مفتاح 'pin_${method}'

    // جلب القيم المخزنة حالياً
    final yemenMobilePin = _getPinForMethod('yemenMobile') ?? '';
    final sabafonPin = _getPinForMethod('sabafon') ?? '';

    final yemenMobileController = TextEditingController(text: yemenMobilePin);
    final sabafonController = TextEditingController(text: sabafonPin);

    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Directionality(
            textDirection: TextDirection.rtl,
            child: Text(
              'إدارة الأرقام السرية',
              style: TextStyle(fontFamily: tajawalFont, fontSize: 15),
            ),
          ),
          content: Directionality(
            textDirection: TextDirection.rtl,
            child: SingleChildScrollView(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  TextField(
                    controller: yemenMobileController,
                    keyboardType: TextInputType.number,
                    obscureText: true,
                    decoration: InputDecoration(
                      labelText: 'الرقم السري ليمن موبايل',
                      prefixIcon: Icon(Icons.lock_outline_rounded),
                    ),
                  ),
                  SizedBox(height: 16),
                  TextField(
                    controller: sabafonController,
                    keyboardType: TextInputType.number,
                    obscureText: true,
                    decoration: InputDecoration(
                      labelText: 'الرقم السري لسبأفون',
                      prefixIcon: Icon(Icons.lock_outline_rounded),
                    ),
                  ),
                ],
              ),
            ),
          ),
          actions: [
            Directionality(
              textDirection: TextDirection.rtl,
              child: TextButton(
                onPressed: () => Navigator.pop(context),
                child: Text('إلغاء', style: TextStyle(fontFamily: tajawalFont)),
              ),
            ),
            Directionality(
              textDirection: TextDirection.rtl,
              child: ElevatedButton(
                onPressed: () async {
                  final newYemenPin = yemenMobileController.text.trim();
                  final newSabafonPin = sabafonController.text.trim();

                  // حفظ القيم في SharedPreferences
                  await _savePinForMethod('yemenMobile', newYemenPin);
                  await _savePinForMethod('sabafon', newSabafonPin);

                  // تحديث قائمة التحويل إذا كانت تستخدم هذه الطرق:
                  setState(() {
                    for (var item in _transferList) {
                      if (item.pin != null) {
                        if (_selectedMethod == 'yemenMobile') {
                          item.pin = newYemenPin;
                        } else if (_selectedMethod == 'sabafon') {
                          item.pin = newSabafonPin;
                        }
                      }
                    }
                  });

                  Navigator.pop(context);
                  _showSnackBar('تم حفظ الأرقام السرية بنجاح');
                },
                child: Text('حفظ', style: TextStyle(fontFamily: tajawalFont)),
              ),
            ),
          ],
        );
      },
    );
  }

  Future<void> _loadTransferHistory() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String>? logs = prefs.getStringList('transferHistory');
    if (logs != null && logs.isNotEmpty) {
      _transferLogs =
          logs.map((e) => json.decode(e) as Map<String, dynamic>).toList();
    } else {
      _transferLogs = [];
    }
  }

  Future<void> _saveTransferHistory() async {
    final prefs = await SharedPreferences.getInstance();
    final List<String> logs = _transferLogs.map((e) => json.encode(e)).toList();
    await prefs.setStringList('transferHistory', logs);
  }

  Future<String?> _askForPin(String method) async {
    final pinController = TextEditingController();

    return showDialog<String>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          title: Text(
            'الرجاء إدخال الرقم السري لطريقة التحويل: ${_getMethodName(method)}',
            style: TextStyle(fontFamily: tajawalFont),
          ),
          content: TextField(
            controller: pinController,
            keyboardType: TextInputType.number,
            obscureText: true,
            decoration: const InputDecoration(
              labelText: 'الرقم السري',
              prefixIcon: Icon(Icons.lock_outline_rounded),
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'إلغاء',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                final pin = pinController.text.trim();
                if (pin.isEmpty) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text(
                        'يرجى إدخال الرقم السري',
                        style: TextStyle(fontFamily: tajawalFont),
                      ),
                    ),
                  );
                  return;
                }
                Navigator.pop(context, pin);
              },
              child: const Text('حفظ'),
            ),
          ],
        );
      },
    );
  }

  Future<void> _savePinForMethod(String method, String pin) async {
    await _prefs?.setString('pin_$method', pin);
  }

  String? _getPinForMethod(String method) {
    return _prefs?.getString('pin_$method');
  }

  Future<void> _addTransferLog(Map<String, dynamic> log) async {
    setState(() {
      _transferLogs.insert(0, log); // أدخل الأحدث في البداية
    });
    await _saveTransferHistory();
  }

  Future<void> _removeTransferLog(int index) async {
    setState(() {
      _transferLogs.removeAt(index);
    });
    await _saveTransferHistory();
  }

  Future<void> _initApp() async {
    _prefs = await SharedPreferences.getInstance();

    final storagePermissionGranted = await requestStoragePermission();
    if (!storagePermissionGranted) {
      _showSnackBar('يرجى منح صلاحيات التخزين لحفظ الملفات');
      // إذا أردت يمكنك عرض حوار للمستخدم أو التوقف عن العمل.
    }
    await _loadTransferHistory();
    _currentBalance = await _loadCurrentBalanceFromJsonData();

    List<String>? amountsStr = _prefs?.getStringList('savedAmounts');
    if (amountsStr != null) {
      _savedAmounts =
          amountsStr
              .map((e) => int.tryParse(e) ?? 0)
              .where((e) => e > 0)
              .toList();
    }

    if (_savedAmounts.isEmpty && !_didShowFavoritesDialog) {
      _didShowFavoritesDialog = true;
      await Future.delayed(Duration.zero);
      await _showFavoritesDialog();
    }

    List<String>? savedTransfers = _prefs?.getStringList('transferList');
    if (savedTransfers != null && savedTransfers.isNotEmpty) {
      _transferList =
          savedTransfers
              .map(
                (e) => TransferItem.fromMap(
                  json.decode(e) as Map<String, dynamic>,
                ),
              )
              .toList();
    } else {
      _transferList = [];
    }

    _selectedMethod = _prefs?.getString('selectedMethod') ?? 'yemenMobile';
    _savedNumbers = _prefs?.getStringList('savedNumbers') ?? [];

    await _requestPermissions();

    if (mounted) setState(() {});
  }

  Future<bool> _requestPermissions() async {
    final phoneStatus = await Permission.phone.status;
    final contactsStatus = await Permission.contacts.status;

    if (!phoneStatus.isGranted || !contactsStatus.isGranted) {
      final status = await [Permission.phone, Permission.contacts].request();

      if (!status[Permission.phone]!.isGranted ||
          !status[Permission.contacts]!.isGranted) {
        _showSnackBar(
          'يجب منح أذونات المكالمات وجهات الاتصال لاستخدام التطبيق',
        );
        return false;
      }
    }
    return true;
  }

  Future<void> _saveTransferList() async {
    final list = _transferList.map((e) => json.encode(e.toMap())).toList();
    await _prefs?.setStringList('transferList', list);
  }

  Future<void> _saveSelectedMethod() async {
    await _prefs?.setString('selectedMethod', _selectedMethod);
  }

  Future<void> _saveSavedNumbers() async {
    await _prefs?.setStringList('savedNumbers', _savedNumbers);
  }

  Future<void> _saveSavedAmounts() async {
    List<String> strList = _savedAmounts.map((e) => e.toString()).toList();
    await _prefs?.setStringList('savedAmounts', strList);
  }

  Future<void> _saveCurrentBalance() async {
    final prefs = await SharedPreferences.getInstance();
    final savedData = prefs.getString('balance_data');
    Map<String, dynamic> jsonData = {};

    if (savedData != null) {
      jsonData = jsonDecode(savedData);
    }

    jsonData['current_balance'] = _currentBalance;

    // تأكد من المحافظة على بقية القيم (مثل additional_balance و total_balance)
    if (!jsonData.containsKey('additional_balance')) {
      jsonData['additional_balance'] = 0;
    }
    if (!jsonData.containsKey('total_balance')) {
      jsonData['total_balance'] =
          _currentBalance + jsonData['additional_balance'];
    } else {
      jsonData['total_balance'] =
          _currentBalance + jsonData['additional_balance'];
    }

    await prefs.setString('balance_data', jsonEncode(jsonData));
  }

  void _showSnackBar(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(
          textDirection: TextDirection.rtl,
          msg,
          style: const TextStyle(
            fontWeight: FontWeight.w500,
            fontFamily: tajawalFont,
          ),
        ),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  Future<String?> _getContactNameFromNumber(String number) async {
    final normalizedNumber = number.replaceAll(RegExp(r'[^\d+]'), '');
    for (var entry in _numberToContactName.entries) {
      final normalizedPhone = entry.key.replaceAll(RegExp(r'[^\d+]'), '');
      if (normalizedPhone == normalizedNumber) {
        return entry.value; // اسم جهة الاتصال أو null
      }
    }
    return null;
  }

  String normalizeYemenPhoneNumber(String phone) {
    String cleaned = phone.replaceAll(
      RegExp(r'[^\d]'),
      '',
    ); // إزالة كل شيء غير الأرقام
    if (cleaned.startsWith('967')) {
      cleaned = cleaned.substring(3);
    }
    if (cleaned.startsWith('0')) {
      cleaned = cleaned.substring(1);
    }
    return cleaned;
  }

  Future<void> _showFavoritesDialog() async {
    final amountsController = TextEditingController();

    await showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          elevation: 4,
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surface,
              borderRadius: BorderRadius.circular(20),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.monetization_on_rounded,
                      color: Theme.of(context).colorScheme.secondary,
                      size: 28,
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'المبالغ المفضلة',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        fontWeight: FontWeight.bold,
                        fontFamily: tajawalFont,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 20),

                if (_savedAmounts.isEmpty)
                  Container(
                    padding: const EdgeInsets.all(16),
                    decoration: BoxDecoration(
                      color: Theme.of(
                        context,
                      ).colorScheme.surfaceVariant.withOpacity(0.2),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Text(
                      'أضف المبالغ التي تريد استخدامها بشكل متكرر',
                      style: Theme.of(
                        context,
                      ).textTheme.bodyMedium?.copyWith(fontFamily: tajawalFont),
                      textAlign: TextAlign.center,
                    ),
                  ),

                if (_savedAmounts.isNotEmpty)
                  Container(
                    constraints: const BoxConstraints(maxHeight: 150),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(12),
                      border: Border.all(
                        color: Theme.of(
                          context,
                        ).colorScheme.outline.withOpacity(0.2),
                      ),
                    ),
                    child: SingleChildScrollView(
                      child: Wrap(
                        spacing: 8,
                        runSpacing: 8,
                        children:
                            _savedAmounts
                                .map(
                                  (amt) => Chip(
                                    label: Text(
                                      _formatWithThousandsSeparator(amt),
                                      style: TextStyle(
                                        fontFamily: tajawalFont,
                                        fontWeight: FontWeight.w600,
                                        color:
                                            Theme.of(
                                              context,
                                            ).colorScheme.onPrimaryContainer,
                                      ),
                                    ),
                                    backgroundColor:
                                        Theme.of(
                                          context,
                                        ).colorScheme.primaryContainer,
                                    deleteIcon: Icon(
                                      Icons.close,
                                      size: 18,
                                      color:
                                          Theme.of(
                                            context,
                                          ).colorScheme.onPrimaryContainer,
                                    ),
                                    onDeleted: () {
                                      setState(() {
                                        _savedAmounts.remove(amt);
                                      });
                                    },
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(8),
                                    ),
                                  ),
                                )
                                .toList(),
                      ),
                    ),
                  ),

                const SizedBox(height: 20),

                TextField(
                  controller: amountsController,
                  keyboardType: TextInputType.number,
                  inputFormatters: [ThousandsSeparatorInputFormatter()],
                  decoration: InputDecoration(
                    suffixIcon: IconButton(
                      icon: Icon(
                        Icons.add_circle,
                        color: Theme.of(context).colorScheme.primary,
                        size: 28,
                      ),
                      onPressed: () {
                        final raw = amountsController.text.replaceAll(',', '');
                        final numAmount = int.tryParse(raw);
                        if (numAmount == null || numAmount <= 0) {
                          _showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
                          return;
                        }
                        if (_savedAmounts.contains(numAmount)) {
                          _showSnackBar('هذا المبلغ موجود بالفعل');
                          return;
                        }
                        setState(() {
                          _savedAmounts.add(numAmount);
                          _savedAmounts.sort();
                          amountsController.clear();
                        });
                      },
                    ),
                    filled: true,
                    fillColor: Theme.of(
                      context,
                    ).colorScheme.surfaceVariant.withOpacity(0.1),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: BorderSide.none,
                    ),
                  ),
                  onSubmitted: (value) {
                    final raw = value.replaceAll(',', '');
                    final numAmount = int.tryParse(raw);
                    if (numAmount == null || numAmount <= 0) {
                      _showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
                      return;
                    }
                    if (_savedAmounts.contains(numAmount)) {
                      _showSnackBar('هذا المبلغ موجود بالفعل');
                      return;
                    }
                    setState(() {
                      _savedAmounts.add(numAmount);
                      _savedAmounts.sort();
                      amountsController.clear();
                    });
                  },
                ),

                const SizedBox(height: 24),

                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      style: TextButton.styleFrom(
                        foregroundColor:
                            Theme.of(context).colorScheme.onSurface,
                      ),
                      child: const Text(
                        'تخطي',
                        style: TextStyle(fontFamily: tajawalFont),
                      ),
                    ),
                    const SizedBox(width: 12),
                    ElevatedButton(
                      onPressed: () async {
                        if (_savedAmounts.isEmpty) {
                          _showSnackBar('الرجاء إدخال مبلغ واحد على الأقل');
                          return;
                        }
                        await _saveSavedAmounts();
                        Navigator.pop(context);
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(context).colorScheme.primary,
                        foregroundColor:
                            Theme.of(context).colorScheme.onPrimary,
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(12),
                        ),
                      ),
                      child: const Text(
                        'حفظ',
                        style: TextStyle(fontFamily: tajawalFont),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  Future<int?> _pickAmountDialog() async {
    if (_savedAmounts.isEmpty) {
      _showSnackBar('لا توجد مبالغ محفوظة. الرجاء إضافتها في الإعدادات.');
      return null;
    }
    int? selectedAmount;

    await showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Padding(
            padding: const EdgeInsets.all(16),
            child: Wrap(
              spacing: 12,
              children:
                  _savedAmounts
                      .map(
                        (amount) => ChoiceChip(
                          label: Text(
                            _formatWithThousandsSeparator(amount),
                            style: TextStyle(
                              fontFamily: tajawalFont,
                              fontWeight: FontWeight.w600,
                              color:
                                  selectedAmount == amount
                                      ? Theme.of(context).colorScheme.onPrimary
                                      : Theme.of(context).colorScheme.primary,
                            ),
                          ),
                          selected: selectedAmount == amount,
                          onSelected: (_) {
                            selectedAmount = amount;
                            Navigator.pop(context);
                          },
                        ),
                      )
                      .toList(),
            ),
          ),
        );
      },
    );

    return selectedAmount;
  }

  Future<void> _showSavedNumbersSelection() async {
    final hasPermission = await _requestPermissions();
    if (!hasPermission) return;

    final contacts = await FlutterContacts.getContacts(
      withProperties: true,
      withThumbnail: false,
    );
    final selectedNumbers = List<String>.from(_savedNumbers);

    final searchController = TextEditingController();
    var searchQuery = '';

    await showModalBottomSheet<void>(
      context: context,
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
      builder: (context) {
        return Directionality(
          textDirection: TextDirection.rtl, // هذا السطر يجعل كل المحتوى RTL
          child: StatefulBuilder(
            builder: (context, setModal) {
              final filteredContacts = _filterContacts(contacts, searchQuery);

              return Container(
                height: MediaQuery.of(context).size.height * 0.9,
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.surface,
                  borderRadius: const BorderRadius.vertical(
                    top: Radius.circular(24),
                  ),
                ),
                padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom,
                ),
                child: Column(
                  children: [
                    // Header with search and title
                    Padding(
                      padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
                      child: Row(
                        textDirection:
                            TextDirection.rtl, // تأكيد اتجاه النص للرأس
                        children: [
                          IconButton(
                            icon: Icon(
                              Icons.close_rounded,
                              color: Theme.of(context).colorScheme.onSurface,
                            ),
                            onPressed: () => Navigator.pop(context),
                            tooltip: 'إغلاق',
                          ),
                          const SizedBox(width: 5),
                          Expanded(
                            child: Padding(
                              padding: const EdgeInsets.only(
                                left: 30,
                              ), // تحريك النص 10 بيكسل إلى اليمين
                              child: Text(
                                'اختر الأرقام المحفوظة',
                                textAlign: TextAlign.center,
                                style: Theme.of(
                                  context,
                                ).textTheme.titleLarge?.copyWith(
                                  fontSize: 17,
                                  fontFamily: tajawalFont,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    // Search bar
                    Padding(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 16,
                        vertical: 8,
                      ),
                      child: TextField(
                        textAlign: TextAlign.right, // محاذاة نص البحث لليمين
                        controller: searchController,
                        decoration: InputDecoration(
                          suffixIcon: const Icon(
                            Icons.search,
                          ), // تغيير الأيقونة للجانب الأيمن
                          hintText: 'ابحث في جهات الاتصال أو الأرقام',
                          isDense: true,
                          filled: true,
                          fillColor: Colors.grey[100],
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.circular(50),
                            borderSide: BorderSide.none,
                          ),
                          contentPadding: const EdgeInsets.symmetric(
                            vertical: 12,
                            horizontal: 16,
                          ),
                        ),
                        onChanged: (value) {
                          setModal(() {
                            searchQuery = value.trim();
                          });
                        },
                      ),
                    ),

                    const SizedBox(height: 8),

                    // Contacts count
                    Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 16),
                      child: Row(
                        textDirection: TextDirection.rtl,
                        children: [
                          Text(
                            '${filteredContacts.length} جهة اتصال',
                            style: Theme.of(
                              context,
                            ).textTheme.bodySmall?.copyWith(
                              fontFamily: tajawalFont,
                              color:
                                  Theme.of(
                                    context,
                                  ).colorScheme.onSurfaceVariant,
                            ),
                          ),
                          const Spacer(),
                          Text(
                            '${selectedNumbers.length} مختارة',
                            style: Theme.of(
                              context,
                            ).textTheme.bodySmall?.copyWith(
                              fontFamily: tajawalFont,
                              color: Theme.of(context).colorScheme.primary,
                            ),
                          ),
                        ],
                      ),
                    ),

                    const Divider(height: 24, thickness: 1),

                    // Contacts list
                    Expanded(
                      child:
                          filteredContacts.isEmpty
                              ? _buildEmptyState(context)
                              : _buildContactsList(
                                context,
                                filteredContacts,
                                selectedNumbers,
                                setModal,
                              ),
                    ),

                    // Bottom buttons
                    _buildBottomButtons(context, selectedNumbers, setModal),
                  ],
                ),
              );
            },
          ),
        );
      },
    );
  }

  // دالة مساعدة لتصفية جهات الاتصال
  List<Contact> _filterContacts(List<Contact> contacts, String query) {
    if (query.isEmpty) return contacts;

    return contacts.where((contact) {
      final contactNameLower = contact.displayName.toLowerCase();
      final queryLower = query.toLowerCase();

      final phonesMatch = contact.phones.any(
        (phone) => phone.number.toLowerCase().contains(queryLower),
      );

      return contactNameLower.contains(queryLower) || phonesMatch;
    }).toList();
  }

  // بناء واجهة الحالة الفارغة
  Widget _buildEmptyState(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(
            Icons.contact_phone_outlined,
            size: 48,
            color: Theme.of(context).colorScheme.outline,
          ),
          const SizedBox(height: 16),
          Text(
            'لا توجد جهات اتصال تطابق البحث',
            textAlign: TextAlign.right,
            style: Theme.of(context).textTheme.bodyMedium?.copyWith(
              fontFamily: tajawalFont,
              color: Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ),
        ],
      ),
    );
  }

  // بناء قائمة جهات الاتصال
  Widget _buildContactsList(
    BuildContext context,
    List<Contact> contacts,
    List<String> selectedNumbers,
    StateSetter setModal,
  ) {
    return ListView.separated(
      keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
      physics: const ClampingScrollPhysics(),
      itemCount: contacts.length,
      separatorBuilder: (_, __) => const Divider(height: 1, indent: 72),
      itemBuilder: (context, index) {
        final contact = contacts[index];
        final phones = contact.phones;

        return Material(
          color: Colors.transparent,
          child: InkWell(
            onTap:
                () => _toggleContactSelection(
                  phones.first.number,
                  selectedNumbers,
                  setModal,
                ),
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
              child: Row(
                textDirection: TextDirection.rtl, // اتجاه الصف من اليمين لليسار
                children: [
                  // Contact avatar
                  _buildContactAvatar(
                    context,
                    contact,
                    selectedNumbers,
                    phones,
                  ),
                  const SizedBox(width: 16),
                  // Contact info
                  _buildContactInfo(context, contact, phones),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  // بناء صورة جهة الاتصال
  Widget _buildContactAvatar(
    BuildContext context,
    Contact contact,
    List<String> selectedNumbers,
    List<Phone> phones,
  ) {
    return Stack(
      children: [
        CircleAvatar(
          radius: 24,
          backgroundImage:
              (contact.thumbnail != null && contact.thumbnail!.isNotEmpty)
                  ? ResizeImage(
                    MemoryImage(contact.thumbnail!),
                    width: 48,
                    height: 48,
                  )
                  : null,
          child:
              (contact.thumbnail == null || contact.thumbnail!.isEmpty)
                  ? Text(
                    contact.initials(),
                    style: const TextStyle(
                      fontFamily: tajawalFont,
                      fontWeight: FontWeight.bold,
                      color: Colors.white,
                      fontSize: 18,
                    ),
                  )
                  : null,
          backgroundColor: Theme.of(context).colorScheme.primary,
        ),
        if (_isContactSelected(phones, selectedNumbers))
          Positioned(
            left: 0, // تغيير الموضع لليسار بدلاً من اليمين
            bottom: 0,
            child: Container(
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                color: Colors.green,
                shape: BoxShape.circle,
                border: Border.all(
                  color: Theme.of(context).colorScheme.surface,
                  width: 2,
                ),
              ),
              child: const Icon(Icons.check, size: 14, color: Colors.white),
            ),
          ),
      ],
    );
  }

  // بناء معلومات جهة الاتصال
  Widget _buildContactInfo(
    BuildContext context,
    Contact contact,
    List<Phone> phones,
  ) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start, // محاذاة النص لليمين
        children: [
          Text(
            contact.displayName,
            textAlign: TextAlign.right,
            style: const TextStyle(
              fontFamily: tajawalFont,
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
          const SizedBox(height: 4),
          ...phones.map(
            (phone) => Text(
              phone.number,
              textAlign: TextAlign.right,
              style: TextStyle(
                fontFamily: tajawalFont,
                fontSize: 14,
                color: Theme.of(context).colorScheme.onSurfaceVariant,
              ),
            ),
          ),
        ],
      ),
    );
  }

  // بناء أزرار القاع
  Widget _buildBottomButtons(
    BuildContext context,
    List<String> selectedNumbers,
    StateSetter setModal,
  ) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Theme.of(context).colorScheme.surface,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.1),
            blurRadius: 8,
            offset: const Offset(0, -4),
          ),
        ],
      ),
      child: Row(
        textDirection: TextDirection.ltr, // اتجاه الصف من اليمين لليسار
        children: [
          Expanded(
            child: OutlinedButton(
              style: OutlinedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
              ),
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'إلغاء',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
          ),
          const SizedBox(width: 12),
          Expanded(
            child: FilledButton(
              style: FilledButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 16),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                ),
                backgroundColor: Theme.of(context).colorScheme.primary,
              ),
              onPressed: () async {
                _savedNumbers = List.from(selectedNumbers);
                await _saveSavedNumbers();
                if (!mounted) return;
                setState(() {});
                Navigator.pop(context);
                _showSnackBar('تم حفظ الأرقام المختارة');
              },
              child: const Text(
                'تأكيد',
                style: TextStyle(
                  fontFamily: tajawalFont,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // تبديل اختيار جهة الاتصال
  void _toggleContactSelection(
    String phoneNumber,
    List<String> selectedNumbers,
    StateSetter setModal,
  ) {
    final normalized = normalizeYemenPhoneNumber(phoneNumber);

    setModal(() {
      if (selectedNumbers.any((num) {
        final n = num.replaceAll(RegExp(r'[^\d+]'), '');
        return n == normalized;
      })) {
        selectedNumbers.removeWhere((num) {
          final n = num.replaceAll(RegExp(r'[^\d+]'), '');
          return n == normalized;
        });
      } else {
        selectedNumbers.add(normalized);
      }
    });
  }

  // التحقق مما إذا كانت جهة الاتصال مختارة
  bool _isContactSelected(List<Phone> phones, List<String> selectedNumbers) {
    return phones.any((phone) {
      final normalized = phone.number.replaceAll(RegExp(r'[^\d+]'), '');
      return selectedNumbers.any((num) {
        final n = num.replaceAll(RegExp(r'[^\d+]'), '');
        return n == normalized;
      });
    });
  }

  Future<void> _showBatchAmountAssignmentDialog(List<String> numbers) async {
    if (numbers.isEmpty) {
      _showSnackBar('لا توجد أرقام لتحديثها');
      return;
    }
    if (_savedAmounts.isEmpty) {
      _showSnackBar('لا توجد مبالغ محفوظة. الرجاء إضافتها في الإعدادات.');
      return;
    }

    List<NumberAmount> tempList = [];
    for (var number in numbers) {
      String? name = await _getContactNameFromNumber(number);
      final existing = _transferList.firstWhere(
        (element) => element.number == number,
        orElse: () => TransferItem(number: number, amount: 0),
      );
      tempList.add(
        NumberAmount(
          number: number,
          displayName: name,
          amount: existing.amount > 0 ? existing.amount : 0,
        ),
      );
    }

    final formKey = GlobalKey<FormState>();

    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text(
            'تعيين مبلغ لكل رقم',
            style: TextStyle(fontFamily: tajawalFont),
          ),
          content: StatefulBuilder(
            builder: (context, setDialogState) {
              return Form(
                key: formKey,
                child: SizedBox(
                  width: double.maxFinite,
                  child: ListView.separated(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    separatorBuilder: (_, __) => const SizedBox(height: 16),
                    itemCount: tempList.length,
                    itemBuilder: (context, index) {
                      final item = tempList[index];
                      return Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.displayName ?? item.number,
                            style: const TextStyle(
                              fontFamily: tajawalFont,
                              fontWeight: FontWeight.w600,
                              fontSize: 16,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                          const SizedBox(height: 8),
                          DropdownButtonFormField<int>(
                            decoration: const InputDecoration(
                              labelText: 'المبلغ',
                              isDense: true,
                            ),
                            items:
                                _savedAmounts
                                    .map(
                                      (e) => DropdownMenuItem(
                                        value: e,
                                        child: Text(
                                          _formatWithThousandsSeparator(e),
                                          style: const TextStyle(
                                            fontFamily: tajawalFont,
                                            fontWeight: FontWeight.w600,
                                          ),
                                        ),
                                      ),
                                    )
                                    .toList(),
                            value: item.amount > 0 ? item.amount : null,
                            onChanged: (val) {
                              setDialogState(() {
                                item.amount = val ?? 0;
                              });
                            },
                            validator: (val) {
                              if (val == null || val <= 0) {
                                return 'يرجى اختيار مبلغ صالح';
                              }
                              return null;
                            },
                            isExpanded: true,
                          ),
                        ],
                      );
                    },
                  ),
                ),
              );
            },
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'إلغاء',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
            FilledButton(
              onPressed: () async {
                if (!formKey.currentState!.validate()) {
                  _showSnackBar('يرجى إدخال جميع المبالغ بشكل صحيح');
                  return;
                }
                for (var item in tempList) {
                  if (!_transferList.any((e) => e.number == item.number)) {
                    String? pinForCurrentMethod = _getPinForMethod(
                      _selectedMethod,
                    );
                    _transferList.add(
                      TransferItem(
                        number: item.number,
                        amount: item.amount,
                        pin:
                            (_selectedMethod == 'yemenMobile' ||
                                    _selectedMethod == 'sabafon')
                                ? ''
                                : null,
                      ),
                    );
                  } else {
                    final existingIndex = _transferList.indexWhere(
                      (e) => e.number == item.number,
                    );
                    if (existingIndex != -1) {
                      _transferList[existingIndex].amount = item.amount;
                      if (_selectedMethod == 'yemenMobile' ||
                          _selectedMethod == 'sabafon') {
                        _transferList[existingIndex].pin ??= '';
                      } else {
                        _transferList[existingIndex].pin = null;
                      }
                    }
                  }
                }
                await _saveTransferList();
                setState(() {});
                Navigator.pop(context);
                _showSnackBar('تم تحديث قائمة التحويل بالمبالغ المحددة');
              },
              child: const Text(
                'حفظ',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
          ],
        );
      },
    );
  }

  String _formatWithThousandsSeparator(int value) {
    final s = value.toString();
    final buffer = StringBuffer();
    int len = s.length;
    for (int i = 0; i < len; i++) {
      buffer.write(s[i]);
      int posFromRight = len - i - 1;
      if (posFromRight % 3 == 0 && i != len - 1) {
        buffer.write(',');
      }
    }
    return buffer.toString();
  }

  // **التعديل الرئيسي: استخدام flutter_phone_direct_caller للاتصال التلقائي**
  Future<void> _startTransferSequence() async {
    if (_transferList.isEmpty) {
      _showSnackBar("لاتوجد عمليات للتحويل");
      return;
    }

    if (_selectedMethod == 'yemenMobile' || _selectedMethod == 'sabafon') {
      String? savedPin = _getPinForMethod(_selectedMethod);

      if (savedPin == null || savedPin.isEmpty) {
        String? pin = await _askForPin(_selectedMethod);
        if (pin == null || pin.isEmpty) {
          _showSnackBar('الرجاء إدخال الرقم السري لإجراء التحويل');
          setState(() {
            _isTransferring = false;
          });
          return;
        }
        savedPin = pin;
        await _savePinForMethod(_selectedMethod, pin);
      }

      // تحديث جميع العمليات بقيمة PIN
      setState(() {
        for (var item in _transferList) {
          item.pin = savedPin;
        }
      });
    }

    int totalAmount = _transferList.fold(0, (sum, item) => sum + item.amount);
    if (totalAmount > _currentBalance) {
      _showSnackBar(
        "الرصيد الحالي (${_formatWithThousandsSeparator(_currentBalance)}) غير كافٍ لإجراء التحويلات (المجموع: ${_formatWithThousandsSeparator(totalAmount)})",
      );
      return;
    }

    // طلب إذن الاتصال CALL_PHONE
    if (!await Permission.phone.isGranted) {
      final status = await Permission.phone.request();
      if (!status.isGranted) {
        _showSnackBar("يجب منح إذن الاتصال لإجراء تحويل الرصيد");
        return;
      }
    }

    final phonePermissionStatus = await Permission.phone.status;
    if (!phonePermissionStatus.isGranted) {
      final status = await Permission.phone.request();
      if (!status.isGranted) {
        _showSnackBar("يجب منح إذن الاتصال لإجراء تحويل الرصيد");
        return;
      }
    }

    setState(() {
      _isTransferring = true;
      _stopTransferRequested = false;
    });
    await _fabAnimationController.forward().orCancel;

    _transferLogs.clear();

    List<TransferItem> tempTransferList = List.from(_transferList);
    List<String> successfullyTransferredNumbers = [];

    for (var i = 0; i < tempTransferList.length; i++) {
      if (_stopTransferRequested) {
        _showSnackBar("تم إيقاف عملية التحويل");
        break;
      }

      var item = tempTransferList[i];
      String ussdCode = _buildUssdCode(item);

      _showSnackBar(
        'جاري تحويل ${_getMethodName(_selectedMethod)}: ${_formatWithThousandsSeparator(item.amount)} إلى ${item.number} (${i + 1}/${tempTransferList.length})',
      );

      try {
        debugPrint("Calling USSD code: $ussdCode");
        bool? called = await FlutterPhoneDirectCaller.callNumber(ussdCode);
        if (called == true) {
          await _addTransferLog({
            'number': item.number,
            'amount': item.amount,
            'success': true,
            'method': _selectedMethod,
            'timestamp': DateTime.now().toIso8601String(),
          });
          successfullyTransferredNumbers.add(item.number);

          setState(() {
            _currentBalance -= item.amount;
          });
          await _saveCurrentBalance();

          await Future.delayed(const Duration(seconds: 10));
        } else {
          await _addTransferLog({
            'number': item.number,
            'amount': item.amount,
            'success': true,
            'method': _selectedMethod,
            'timestamp': DateTime.now().toIso8601String(),
          });
        }
      } catch (e) {
        await _addTransferLog({
          'number': item.number,
          'amount': item.amount,
          'success': true,
          'method': _selectedMethod,
          'timestamp': DateTime.now().toIso8601String(),
        });
      }
    }

    setState(() {
      for (var number in successfullyTransferredNumbers) {
        _transferList.removeWhere((t) => t.number == number);
        _savedNumbers.removeWhere(
          (num) => _normalizeNumber(num) == _normalizeNumber(number),
        );
        if (_selectedQuickNumber == number) _selectedQuickNumber = null;
      }
    });

    await _saveTransferList();
    await _saveSavedNumbers();

    setState(() {
      _isTransferring = false;
    });
    await _fabAnimationController.reverse().orCancel;

    if (!_stopTransferRequested) {
      _showSnackBar("تمت جميع عمليات التحويل");
    }
    _fabAnimationController.value = 1;
  }

  String _normalizeNumber(String number) {
    return normalizeYemenPhoneNumber(number);
  }

  String _getMethodName(String method) {
    switch (method) {
      case 'yemenMobile':
        return 'يمن موبايل';
      case 'y':
        return 'واي';
      case 'sabafon':
        return 'سبأفون';
      case 'you':
        return 'يو';
      default:
        return method;
    }
  }

  String _buildUssdCode(TransferItem item) {
    final number = item.number;
    final amount = item.amount.toString();
    final pin = item.pin ?? '';

    String code = '';

    switch (_selectedMethod) {
      case 'yemenMobile':
        if (pin.isEmpty) {
          // إذا PIN فارغ، رمز بدون PIN
          code = '*888*$amount*$number#';
        } else {
          code = '*888*$amount*$number*$pin#';
        }
        break;
      case 'sabafon':
        if (pin.isEmpty) {
          code = '*123*$number*$amount#';
        } else {
          code = '*123*$pin*$number*$amount#';
        }
        break;
      case 'y':
        code = '*109*$amount*$number#';
        break;
      case 'you':
        code = '*130*$number*$amount#';
        break;
      default:
        code = '';
    }

    return code.replaceAll('#', Uri.encodeComponent('#'));
  }

  void _showTransferLogsDialog() {
    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          child: ConstrainedBox(
            constraints: BoxConstraints(
              maxWidth: MediaQuery.of(context).size.width * 0.9,
              maxHeight: MediaQuery.of(context).size.height * 0.8,
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                // Header with title and close button
                Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Theme.of(context).colorScheme.primaryContainer,
                    borderRadius: const BorderRadius.vertical(
                      top: Radius.circular(16),
                    ),
                  ),
                  child: Row(
                    children: [
                      IconButton(
                        icon: Icon(
                          Icons.close,
                          color:
                              Theme.of(context).colorScheme.onPrimaryContainer,
                        ),
                        onPressed: () => Navigator.pop(context),
                      ),
                      Expanded(
                        child: Text(
                          'سجل عمليات التحويل',
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontFamily: tajawalFont,
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color:
                                Theme.of(
                                  context,
                                ).colorScheme.onPrimaryContainer,
                          ),
                        ),
                      ),
                      const SizedBox(
                        width: 48,
                      ), // Balance the row with close button
                    ],
                  ),
                ),

                // Content area
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 8),
                    child:
                        _transferLogs.isEmpty
                            ? Center(
                              child: Column(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  Icon(
                                    Icons.history_toggle_off_rounded,
                                    size: 48,
                                    color: Theme.of(context)
                                        .colorScheme
                                        .onSurfaceVariant
                                        .withOpacity(0.5),
                                  ),
                                  const SizedBox(height: 16),
                                  Text(
                                    'لا توجد عمليات تحويل حتى الآن',
                                    style: Theme.of(
                                      context,
                                    ).textTheme.bodyMedium?.copyWith(
                                      fontFamily: tajawalFont,
                                      color: Colors.black,
                                    ),
                                  ),
                                ],
                              ),
                            )
                            : Directionality(
                              textDirection: TextDirection.rtl,
                              child: ListView.separated(
                                shrinkWrap: true,
                                physics: const ClampingScrollPhysics(),
                                itemCount: _transferLogs.length,
                                separatorBuilder:
                                    (_, __) => Divider(
                                      height: 1,
                                      thickness: 1,
                                      color: Theme.of(
                                        context,
                                      ).dividerColor.withOpacity(0.1),
                                    ),
                                itemBuilder: (_, i) {
                                  final log = _transferLogs[i];
                                  final success = log['success'] as bool;
                                  final timestamp =
                                      log['timestamp'] != null
                                          ? DateTime.parse(log['timestamp'])
                                          : null;
                                  final timeFormatted =
                                      timestamp != null
                                          ? '${timestamp.year}-${timestamp.month.toString().padLeft(2, '0')}-${timestamp.day.toString().padLeft(2, '0')} ${timestamp.hour.toString().padLeft(2, '0')}:${timestamp.minute.toString().padLeft(2, '0')}'
                                          : '';

                                  return Container(
                                    margin: const EdgeInsets.symmetric(
                                      vertical: 4,
                                    ),
                                    decoration: BoxDecoration(
                                      color: Theme.of(context)
                                          .colorScheme
                                          .surfaceVariant
                                          .withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: ListTile(
                                      contentPadding:
                                          const EdgeInsets.symmetric(
                                            horizontal: 12,
                                            vertical: 8,
                                          ),
                                      leading: Container(
                                        width: 40,
                                        height: 40,
                                        decoration: BoxDecoration(
                                          color:
                                              success
                                                  ? Theme.of(
                                                    context,
                                                  ).colorScheme.primaryContainer
                                                  : Theme.of(
                                                    context,
                                                  ).colorScheme.errorContainer,
                                          shape: BoxShape.circle,
                                        ),
                                        child: Icon(
                                          success
                                              ? Icons.check_rounded
                                              : Icons.close_rounded,
                                          color:
                                              success
                                                  ? Theme.of(
                                                    context,
                                                  ).colorScheme.primary
                                                  : Theme.of(
                                                    context,
                                                  ).colorScheme.error,
                                          size: 20,
                                        ),
                                      ),
                                      title: Text(
                                        '${_getMethodName(log['method'])} - ${log['number']}',
                                        style: TextStyle(
                                          fontWeight: FontWeight.w600,
                                          fontFamily: tajawalFont,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.onSurface,
                                        ),
                                      ),
                                      subtitle: Padding(
                                        padding: const EdgeInsets.only(top: 4),
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            Text(
                                              'المبلغ: ${_formatWithThousandsSeparator(log['amount'] ?? 0)} (${convertNumberToArabicWords(log['amount'] ?? 0)})',
                                              style: TextStyle(
                                                fontFamily: tajawalFont,
                                                color:
                                                    Theme.of(context)
                                                        .colorScheme
                                                        .onSurfaceVariant,
                                              ),
                                            ),
                                            if (timeFormatted.isNotEmpty)
                                              Padding(
                                                padding: const EdgeInsets.only(
                                                  top: 2,
                                                ),
                                                child: Text(
                                                  'الوقت: $timeFormatted',
                                                  style: TextStyle(
                                                    fontFamily: tajawalFont,
                                                    fontSize: 12,
                                                    color: Theme.of(context)
                                                        .colorScheme
                                                        .onSurfaceVariant
                                                        .withOpacity(0.7),
                                                  ),
                                                ),
                                              ),
                                            if (log['error'] != null)
                                              Padding(
                                                padding: const EdgeInsets.only(
                                                  top: 4,
                                                ),
                                                child: Text(
                                                  'خطأ: ${log['error']}',
                                                  style: TextStyle(
                                                    fontFamily: tajawalFont,
                                                    fontSize: 12,
                                                    color:
                                                        Theme.of(
                                                          context,
                                                        ).colorScheme.error,
                                                  ),
                                                ),
                                              ),
                                          ],
                                        ),
                                      ),
                                      trailing: IconButton(
                                        icon: Icon(
                                          Icons.delete_forever,
                                          color: Theme.of(
                                            context,
                                          ).colorScheme.error.withOpacity(0.7),
                                          size: 20,
                                        ),
                                        tooltip: 'حذف السجل',
                                        onPressed: () {
                                          _removeTransferLog(i);
                                          Navigator.pop(context);
                                          Future.delayed(
                                            const Duration(milliseconds: 100),
                                            _showTransferLogsDialog,
                                          );
                                        },
                                      ),
                                    ),
                                  );
                                },
                              ),
                            ),
                  ),
                ),

                // Footer with action buttons
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Theme.of(
                      context,
                    ).colorScheme.surfaceVariant.withOpacity(0.1),
                    borderRadius: const BorderRadius.vertical(
                      bottom: Radius.circular(16),
                    ),
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      // Export button
                      Expanded(
                        child: OutlinedButton.icon(
                          style: OutlinedButton.styleFrom(
                            foregroundColor:
                                Theme.of(context).colorScheme.onSurface,
                            side: BorderSide(
                              color: Theme.of(
                                context,
                              ).colorScheme.outline.withOpacity(0.2),
                            ),
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          onPressed: () {
                            Navigator.pop(context);
                            _exportTransferLogsToCsv();
                          },
                          icon: Icon(
                            Icons.file_download_rounded,
                            size: 20,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                          label: Text(
                            'تصدير',
                            style: TextStyle(
                              fontFamily: tajawalFont,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),

                      const SizedBox(width: 8),

                      // Delete all button
                      Expanded(
                        child: FilledButton.icon(
                          style: FilledButton.styleFrom(
                            backgroundColor:
                                Theme.of(context).colorScheme.errorContainer,
                            foregroundColor:
                                Theme.of(context).colorScheme.onErrorContainer,
                            padding: const EdgeInsets.symmetric(vertical: 12),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(12),
                            ),
                          ),
                          onPressed:
                              _transferLogs.isEmpty
                                  ? null
                                  : () {
                                    setState(() {
                                      _transferLogs.clear();
                                    });
                                    _saveTransferHistory();
                                    Navigator.pop(context);
                                    _showSnackBar('تم حذف جميع سجلات التحويل');
                                  },
                          icon: Icon(
                            Icons.delete_forever_rounded,
                            size: 20,
                            color:
                                Theme.of(context).colorScheme.onErrorContainer,
                          ),
                          label: Text(
                            'حذف الكل',
                            style: TextStyle(
                              fontFamily: tajawalFont,
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showAmountsManagementDialog() async {
    final amountsController = TextEditingController();
    bool isValidInput(String value) {
      final raw = value.replaceAll(',', '');
      final numAmount = int.tryParse(raw);
      return numAmount != null &&
          numAmount > 0 &&
          !_savedAmounts.contains(numAmount);
    }

    void addAmount(
      String value,
      void Function(void Function()) setDialogState,
    ) {
      final raw = value.replaceAll(',', '');
      final numAmount = int.tryParse(raw);
      if (numAmount == null || numAmount <= 0) {
        _showSnackBar('يرجى إدخال مبلغ صحيح أكبر من صفر');
        return;
      }
      if (_savedAmounts.contains(numAmount)) {
        _showSnackBar('هذا المبلغ موجود بالفعل');
        return;
      }
      setDialogState(() {
        _savedAmounts.add(numAmount);
        _savedAmounts.sort();
        amountsController.clear();
      });
    }

    await showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text(
            'إدارة المبالغ المحفوظة',
            style: TextStyle(fontFamily: tajawalFont),
            textAlign: TextAlign.center,
          ),
          content: StatefulBuilder(
            builder: (context, setDialogState) {
              return SizedBox(
                width: double.maxFinite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    if (_savedAmounts.isEmpty)
                      Padding(
                        padding: const EdgeInsets.symmetric(vertical: 12),
                        child: Text(
                          'لا توجد مبالغ محفوظة حالياً',
                          style: Theme.of(
                            context,
                          ).textTheme.bodyMedium?.copyWith(
                            fontFamily: tajawalFont,
                            color:
                                Theme.of(context).colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ),
                    if (_savedAmounts.isNotEmpty)
                      Container(
                        constraints: BoxConstraints(maxHeight: 150),
                        child: SingleChildScrollView(
                          child: Wrap(
                            spacing: 8,
                            runSpacing: 6,
                            children:
                                _savedAmounts
                                    .map(
                                      (amt) => Tooltip(
                                        message: 'حذف هذا المبلغ',
                                        child: Chip(
                                          label: Text(
                                            _formatWithThousandsSeparator(amt),
                                            style: const TextStyle(
                                              fontFamily: tajawalFont,
                                              fontWeight: FontWeight.w600,
                                            ),
                                          ),
                                          backgroundColor:
                                              Theme.of(
                                                context,
                                              ).colorScheme.primaryContainer,
                                          shape: RoundedRectangleBorder(
                                            borderRadius: BorderRadius.circular(
                                              20,
                                            ),
                                          ),
                                          onDeleted: () {
                                            setDialogState(() {
                                              _savedAmounts.remove(amt);
                                            });
                                          },
                                          deleteIconColor:
                                              Theme.of(
                                                context,
                                              ).colorScheme.error,
                                        ),
                                      ),
                                    )
                                    .toList(),
                          ),
                        ),
                      ),
                    const Divider(height: 25, thickness: 1),
                    TextField(
                      controller: amountsController,
                      keyboardType: TextInputType.number,
                      inputFormatters: [ThousandsSeparatorInputFormatter()],
                      decoration: InputDecoration(
                        labelText: 'إضافة مبلغ جديد',
                        suffixIcon: IconButton(
                          icon: const Icon(Icons.add_circle_rounded),
                          tooltip: 'إضافة المبلغ',
                          onPressed:
                              isValidInput(amountsController.text)
                                  ? () => addAmount(
                                    amountsController.text,
                                    setDialogState,
                                  )
                                  : null,
                        ),
                      ),
                      onChanged: (value) {
                        setDialogState(() {}); // لتحديث زر الإضافة
                      },
                      onSubmitted: (value) {
                        addAmount(value, setDialogState);
                      },
                    ),
                  ],
                ),
              );
            },
          ),
          actionsAlignment: MainAxisAlignment.spaceBetween,
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text(
                'إغلاق',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
            FilledButton.tonal(
              onPressed: () async {
                await _saveSavedAmounts();
                Navigator.pop(context);
                _showSnackBar('تم حفظ المبالغ بنجاح');
              },
              child: const Text(
                'حفظ',
                style: TextStyle(fontFamily: tajawalFont),
              ),
            ),
          ],
        );
      },
    );
  }

  void _stopTransferSequence() {
    if (_isTransferring) {
      setState(() {
        _stopTransferRequested = true;
      });
      _showSnackBar("تم طلب إيقاف عملية التحويل");
    }
  }

  Widget _buildCurrentTransferMethodSection() {
    final methodNames = {
      'yemenMobile': 'يمن موبايل',
      'y': 'واي',
      'sabafon': 'سبأفون',
      'you': 'يو',
    };

    final methodIcons = {
      'yemenMobile': Icons.sim_card,
      'y': Icons.sim_card,
      'sabafon': Icons.sim_card,
      'you': Icons.sim_card,
    };

    final methodName = methodNames[_selectedMethod] ?? _selectedMethod;
    final methodIcon = methodIcons[_selectedMethod] ?? Icons.sync;

    return Directionality(
      textDirection: TextDirection.rtl,
      child: Card(
        margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
        elevation: 2,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(18)),
        child: InkWell(
          borderRadius: BorderRadius.circular(18),
          onTap: () async {
            final selected = await showDialog<String>(
              context: context,
              builder:
                  (context) => Directionality(
                    textDirection: TextDirection.rtl,
                    child: SimpleDialog(
                      titlePadding: const EdgeInsets.fromLTRB(24, 20, 24, 10),
                      contentPadding: const EdgeInsets.symmetric(
                        horizontal: 12,
                      ),
                      title: Text(
                        'اختر طريقة التحويل',
                        style: TextStyle(
                          fontFamily: tajawalFont,
                          color: Theme.of(context).colorScheme.onSurface,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      children:
                          methodNames.entries.map((entry) {
                            final isSelected = entry.key == _selectedMethod;
                            return SimpleDialogOption(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 8,
                              ),
                              onPressed:
                                  () => Navigator.of(context).pop(entry.key),
                              child: Container(
                                padding: const EdgeInsets.all(8),
                                decoration: BoxDecoration(
                                  color:
                                      isSelected
                                          ? Theme.of(
                                            context,
                                          ).colorScheme.primary.withOpacity(0.1)
                                          : Colors.transparent,
                                  borderRadius: BorderRadius.circular(8),
                                ),
                                child: Row(
                                  children: [
                                    Icon(
                                      methodIcons[entry.key]!,
                                      color:
                                          isSelected
                                              ? Theme.of(
                                                context,
                                              ).colorScheme.primary
                                              : Theme.of(
                                                context,
                                              ).colorScheme.onSurfaceVariant,
                                      size: 24,
                                    ),
                                    const SizedBox(width: 16),
                                    Expanded(
                                      child: Text(
                                        entry.value,
                                        style: TextStyle(
                                          fontFamily: tajawalFont,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.onSurface,
                                        ),
                                      ),
                                    ),
                                    if (isSelected)
                                      Icon(
                                        Icons.check,
                                        color:
                                            Theme.of(
                                              context,
                                            ).colorScheme.primary,
                                      ),
                                  ],
                                ),
                              ),
                            );
                          }).toList(),
                    ),
                  ),
            );

            if (selected != null && selected != _selectedMethod) {
              if (selected == 'yemenMobile' || selected == 'sabafon') {
                String? savedPin = _getPinForMethod(selected);
                if (savedPin == null) {
                  String? pin = await _askForPin(selected);
                  if (pin == null) return;
                  await _savePinForMethod(selected, pin);
                  savedPin = pin;
                }
                if (mounted) {
                  setState(() {
                    _selectedMethod = selected;
                    for (var item in _transferList) {
                      item.pin = savedPin;
                    }
                  });
                }
                await _saveSelectedMethod();
              } else {
                if (mounted) {
                  setState(() {
                    _selectedMethod = selected;
                    for (var item in _transferList) {
                      item.pin = null;
                    }
                  });
                }
                await _saveSelectedMethod();
              }
              if (mounted) {
                _showSnackBar(
                  'تم تغيير طريقة التحويل إلى ${methodNames[selected]}',
                );
              }
            }
          },
          highlightColor: Theme.of(
            context,
          ).colorScheme.primary.withOpacity(0.1),
          splashColor: Theme.of(context).colorScheme.primary.withOpacity(0.2),
          child: Padding(
            padding: const EdgeInsets.all(18),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: Theme.of(
                          context,
                        ).colorScheme.primary.withOpacity(0.1),
                        shape: BoxShape.circle,
                      ),
                      child: Icon(
                        Icons.swap_horiz,
                        size: 24,
                        color: Theme.of(context).colorScheme.primary,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Text(
                      'طريقة التحويل الحالية',
                      style: Theme.of(context).textTheme.titleLarge?.copyWith(
                        fontFamily: tajawalFont,
                        fontWeight: FontWeight.bold,
                        color: Theme.of(context).colorScheme.onSurface,
                      ),
                    ),
                    const Spacer(),
                    Tooltip(
                      message: 'انقر لتغيير طريقة التحويل',
                      child: Icon(
                        Icons.touch_app_rounded,
                        size: 20,
                        color: Theme.of(
                          context,
                        ).colorScheme.primary.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 16),
                Container(
                  padding: const EdgeInsets.all(14),
                  decoration: BoxDecoration(
                    color: Theme.of(
                      context,
                    ).colorScheme.surfaceVariant.withOpacity(0.2),
                    borderRadius: BorderRadius.circular(14),
                  ),
                  child: Row(
                    children: [
                      Container(
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color: Theme.of(context).colorScheme.surfaceVariant,
                          borderRadius: BorderRadius.circular(12),
                        ),
                        child: Icon(
                          methodIcon,
                          size: 32,
                          color: Theme.of(context).colorScheme.primary,
                        ),
                      ),
                      const SizedBox(width: 14),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              methodName,
                              style: Theme.of(
                                context,
                              ).textTheme.titleMedium?.copyWith(
                                fontFamily: tajawalFont,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Row(
                              children: [
                                Text(
                                  'آلية لتحويل الرصيد دفعة واحدة.',
                                  style: Theme.of(
                                    context,
                                  ).textTheme.bodySmall?.copyWith(
                                    fontFamily: tajawalFont,
                                    color:
                                        Theme.of(
                                          context,
                                        ).colorScheme.onSurfaceVariant,
                                    fontSize: 12,
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Icon(
                                  Icons.info_outline_rounded,
                                  size: 16,
                                  color: Theme.of(
                                    context,
                                  ).colorScheme.primary.withOpacity(0.6),
                                ),
                              ],
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget fabChild =
        _isTransferring
            ? Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 20,
                  height: 20,
                  child: CircularProgressIndicator(
                    color: Theme.of(context).colorScheme.onPrimary,
                    strokeWidth: 3,
                  ),
                ),
                const SizedBox(width: 8),
                const Text(
                  'إيقاف التحويل',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontFamily: tajawalFont,
                  ),
                ),
              ],
            )
            : Row(
              mainAxisSize: MainAxisSize.min,
              children: const [
                SizedBox(width: 8),
                Text(
                  'إجراء التحويلات',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontFamily: tajawalFont,
                  ),
                ),
              ],
            );

    return Scaffold(
      appBar: AppBar(
        toolbarHeight: 100,
        title: Row(
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(),
                        child: Image.asset(
                          'assets/vibrafone_logo.png', // تأكد من أن المسار صحيح
                          width: 28,
                          height: 28,
                        ),
                      ),
                      SizedBox(width: 1),
                      Text(
                        'تحويل ذكي',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                          fontFamily: tajawalFont,
                          color: Colors.white,
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  InkWell(
                    borderRadius: BorderRadius.circular(12),
                    onTap: _showBalanceDialog,
                    child: Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 10,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: Colors.white.withOpacity(0.15),
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Row(
                        mainAxisSize: MainAxisSize.min,
                        textDirection: TextDirection.rtl,
                        children: [
                          Icon(
                            Icons.account_balance_wallet_rounded,
                            size: 16,
                            color: Colors.white,
                          ),
                          const SizedBox(width: 5),
                          Text(
                            ':الرصيد',
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              fontFamily: tajawalFont,
                              color: Colors.white,
                            ),
                          ),
                          const SizedBox(width: 3),
                          Flexible(
                            child: Text(
                              _formatWithThousandsSeparator(_currentBalance),
                              style: TextStyle(
                                fontSize: 14,
                                fontWeight: FontWeight.w600,
                                fontFamily: tajawalFont,
                                color: Colors.white,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                              textDirection:
                                  TextDirection
                                      .ltr, // تأكد من أن الرقم يظهر من اليسار لليمين
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),

        actions: [
          _buildAppBarActionButton(
            icon: Icons.attach_money_rounded,
            tooltip: 'إدارة المبالغ المحفوظة',
            onPressed: _showAmountsManagementDialog,
          ),
          _buildAppBarActionButton(
            icon: Icons.contacts_rounded,
            tooltip: 'إدارة الأرقام المحفوظة',
            onPressed: _showSavedNumbersSelection,
          ),
          _buildAppBarActionButton(
            icon: Icons.lock_rounded,
            tooltip: 'إدارة الرقم السري',
            onPressed: _showPinManagementDialog,
          ),
          if (_transferLogs.isNotEmpty)
            _buildAppBarActionButton(
              icon: Icons.history_rounded,
              tooltip: 'سجل التحويلات السابقة',
              onPressed: _showTransferLogsDialog,
            ),
        ],

        flexibleSpace: Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [lightColorScheme.primary, Color(0xFFE65100)],
              begin: Alignment.topLeft,
              end: Alignment.bottomRight,
            ),
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(20)),
          ),
        ),
        elevation: 8,
        shadowColor: lightColorScheme.primary.withOpacity(0.5),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.vertical(bottom: Radius.circular(20)),
        ),
      ),

      floatingActionButton: ScaleTransition(
        scale: _fabAnimation,
        child: FloatingActionButton.extended(
          onPressed:
              _isTransferring ? _stopTransferSequence : _startTransferSequence,
          icon:
              _isTransferring
                  ? null
                  : const Icon(Icons.currency_exchange_rounded),
          label: fabChild,
          elevation: 6,
          backgroundColor: Theme.of(context).colorScheme.primary,
          foregroundColor: Theme.of(context).colorScheme.onPrimary,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
        ),
      ),

      body: Column(
        children: [
          _buildCurrentTransferMethodSection(),
          if (_savedNumbers.isNotEmpty)
            Padding(
              padding: const EdgeInsets.fromLTRB(8, 3, 16, 8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(
                      0,
                      3,
                      8,
                      3,
                    ), // ازاحة بسيطة لليسار
                    child: Text(
                      'قم بالتحديد لإضافة رصيد',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                        fontFamily: tajawalFont,
                      ),
                    ),
                  ),
                  const SizedBox(height: 8),
                  SizedBox(
                    height: 55,
                    child: FutureBuilder<List<Map<String, String?>>>(
                      future: Future.wait(
                        _savedNumbers.map((number) async {
                          final name = await _getContactNameFromNumber(number);
                          return {'number': number, 'name': name};
                        }).toList(),
                      ),
                      builder: (context, snapshot) {
                        if (!snapshot.hasData) {
                          return const Center(
                            child: CircularProgressIndicator(),
                          );
                        }
                        final data = snapshot.data!;
                        return ListView.separated(
                          scrollDirection: Axis.horizontal,
                          itemCount: data.length,
                          separatorBuilder:
                              (_, __) => const SizedBox(width: 12),
                          itemBuilder: (context, index) {
                            final item = data[index];
                            final number = item['number']!;
                            final displayText =
                                item['name']?.isNotEmpty == true
                                    ? item['name']
                                    : number;
                            final bool isSelected =
                                _selectedQuickNumber == number;

                            String initials = '';
                            if (item['name']?.isNotEmpty == true) {
                              final parts = displayText!.trim().split(' ');
                              if (parts.length == 1) {
                                initials = parts[0][0];
                              } else if (parts.length > 1) {
                                initials = parts[0][0] + parts[1][0];
                              }
                            } else {
                              initials = number.substring(0, 2);
                            }
                            initials = initials.toUpperCase();

                            return GestureDetector(
                              onTap: () async {
                                if (isSelected) {
                                  setState(() {
                                    _selectedQuickNumber = null;
                                  });
                                } else {
                                  final defaultAmount =
                                      _savedAmounts.isNotEmpty
                                          ? _savedAmounts.first
                                          : 0;

                                  setState(() {
                                    _selectedQuickNumber = number;

                                    if (!_transferList.any(
                                      (e) => e.number == number,
                                    )) {
                                      _transferList.add(
                                        TransferItem(
                                          number: number,
                                          amount: defaultAmount,
                                          pin:
                                              (_selectedMethod ==
                                                          'yemenMobile' ||
                                                      _selectedMethod ==
                                                          'sabafon')
                                                  ? _getPinForMethod(
                                                        _selectedMethod,
                                                      ) ??
                                                      ''
                                                  : null,
                                        ),
                                      );
                                    }

                                    _savedNumbers.removeWhere(
                                      (num) =>
                                          _normalizeNumber(num) ==
                                          _normalizeNumber(number),
                                    );
                                  });

                                  // احفظ البيانات _بعد_ تحديث حالة الواجهة وليس داخل setState
                                  await _saveTransferList();
                                  await _saveSavedNumbers();
                                }
                              },
                              child: Container(
                                width: 200,
                                padding: const EdgeInsets.symmetric(
                                  horizontal: 12,
                                  vertical: 5,
                                ),
                                decoration: BoxDecoration(
                                  color:
                                      isSelected
                                          ? Theme.of(
                                            context,
                                          ).colorScheme.primary
                                          : Theme.of(
                                            context,
                                          ).colorScheme.surfaceVariant,
                                  borderRadius: BorderRadius.circular(50),
                                ),
                                child: Row(
                                  children: [
                                    CircleAvatar(
                                      radius: 20,
                                      backgroundColor:
                                          isSelected
                                              ? Theme.of(
                                                context,
                                              ).colorScheme.surface
                                              : Theme.of(
                                                context,
                                              ).colorScheme.primary,
                                      child: Text(
                                        initials,
                                        style: TextStyle(
                                          color:
                                              isSelected
                                                  ? Theme.of(
                                                    context,
                                                  ).colorScheme.primary
                                                  : Theme.of(
                                                    context,
                                                  ).colorScheme.onPrimary,
                                          fontFamily: tajawalFont,
                                          fontWeight: FontWeight.bold,
                                        ),
                                      ),
                                    ),
                                    const SizedBox(width: 12),
                                    Expanded(
                                      child: Text(
                                        displayText ?? number,
                                        style: TextStyle(
                                          color:
                                              isSelected
                                                  ? Theme.of(
                                                    context,
                                                  ).colorScheme.onPrimary
                                                  : Theme.of(
                                                    context,
                                                  ).colorScheme.onSurface,
                                          fontFamily: tajawalFont,
                                          fontWeight: FontWeight.w600,
                                        ),
                                        maxLines: 2,
                                        overflow: TextOverflow.ellipsis,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            );
                          },
                        );
                      },
                    ),
                  ),

                  // زر حذف جهة الاتصال المحددة يظهر فقط عند اختيار رقم سريع
                ],
              ),
            ),
          const Divider(height: 5),
          Expanded(
            child: Directionality(
              textDirection: TextDirection.rtl,
              child:
                  _transferList.isEmpty
                      ? Center(
                        child: Column(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.swap_horiz_rounded,
                              size: 72,
                              color: Theme.of(
                                context,
                              ).colorScheme.primary.withOpacity(0.5),
                            ),
                            const SizedBox(height: 20),
                            Text(
                              'لا توجد عمليات تحويل',
                              style: Theme.of(
                                context,
                              ).textTheme.titleLarge?.copyWith(
                                fontFamily: tajawalFont,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                            ),
                            const SizedBox(height: 12),
                            Text(
                              'انقر على زر الإضافة لبدء إنشاء قائمة التحويلات',
                              textAlign: TextAlign.center,
                              style: Theme.of(
                                context,
                              ).textTheme.bodyMedium?.copyWith(
                                fontFamily: tajawalFont,
                                color:
                                    Theme.of(
                                      context,
                                    ).colorScheme.onSurfaceVariant,
                              ),
                            ),
                          ],
                        ),
                      )
                      : Column(
                        children: [
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8.0),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Icon(
                                  Icons.arrow_back,
                                  size: 16,
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  'اسحب للتعديل',
                                  style: TextStyle(
                                    fontFamily: tajawalFont,
                                    color:
                                        Theme.of(context).colorScheme.primary,
                                    fontSize: 12,
                                  ),
                                ),
                                const SizedBox(width: 16),
                                Icon(
                                  Icons.arrow_forward,
                                  size: 16,
                                  color: Theme.of(context).colorScheme.error,
                                ),
                                const SizedBox(width: 4),
                                Text(
                                  'اسحب للحذف',
                                  style: TextStyle(
                                    fontFamily: tajawalFont,
                                    color: Theme.of(context).colorScheme.error,
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Expanded(
                            child: ListView.builder(
                              physics: const BouncingScrollPhysics(),
                              padding: const EdgeInsets.only(bottom: 96),
                              itemCount: _transferList.length,
                              itemBuilder: (context, index) {
                                final item = _transferList[index];

                                return Dismissible(
                                  key: Key('${item.number}_$index'),
                                  background: Container(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 8,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          Theme.of(
                                            context,
                                          ).colorScheme.errorContainer,
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    alignment: Alignment.centerLeft,
                                    padding: const EdgeInsets.only(left: 24),
                                    child: Row(
                                      mainAxisAlignment:
                                          MainAxisAlignment.start,
                                      children: [
                                        Icon(
                                          Icons.delete_forever_rounded,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.error,
                                          size: 28,
                                        ),
                                        const SizedBox(width: 8),
                                        Text(
                                          'حذف',
                                          style: TextStyle(
                                            fontFamily: tajawalFont,
                                            color:
                                                Theme.of(
                                                  context,
                                                ).colorScheme.error,
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ],
                                    ),
                                  ),
                                  secondaryBackground: Container(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 8,
                                    ),
                                    decoration: BoxDecoration(
                                      color:
                                          Theme.of(
                                            context,
                                          ).colorScheme.primaryContainer,
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    alignment: Alignment.centerRight,
                                    padding: const EdgeInsets.only(right: 24),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: [
                                        Text(
                                          'تعديل',
                                          style: TextStyle(
                                            fontFamily: tajawalFont,
                                            color:
                                                Theme.of(
                                                  context,
                                                ).colorScheme.primary,
                                            fontSize: 16,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                        const SizedBox(width: 8),
                                        Icon(
                                          Icons.edit_rounded,
                                          color:
                                              Theme.of(
                                                context,
                                              ).colorScheme.primary,
                                          size: 28,
                                        ),
                                      ],
                                    ),
                                  ),
                                  direction: DismissDirection.horizontal,
                                  confirmDismiss: (direction) async {
                                    if (direction ==
                                        DismissDirection.endToStart) {
                                      _editTransfer(index);
                                      return false;
                                    }
                                    return await _showDeleteConfirmation(
                                      context,
                                    );
                                  },
                                  onDismissed:
                                      (direction) => _removeTransferAt(index),
                                  child: Card(
                                    margin: const EdgeInsets.symmetric(
                                      horizontal: 16,
                                      vertical: 8,
                                    ),
                                    shape: RoundedRectangleBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    elevation: 1,
                                    child: ListTile(
                                      contentPadding:
                                          const EdgeInsets.symmetric(
                                            horizontal: 16,
                                            vertical: 8,
                                          ),
                                      leading: Container(
                                        width: 44,
                                        height: 44,
                                        decoration: BoxDecoration(
                                          color:
                                              _amountEdited[item.number] == true
                                                  ? Colors.green.withOpacity(
                                                    0.1,
                                                  )
                                                  : Theme.of(context)
                                                      .colorScheme
                                                      .primaryContainer,
                                          shape: BoxShape.circle,
                                        ),
                                        child: Icon(
                                          _amountEdited[item.number] == true
                                              ? Icons.check_circle_rounded
                                              : Icons.person_rounded,
                                          color:
                                              _amountEdited[item.number] == true
                                                  ? Colors.green
                                                  : Theme.of(
                                                    context,
                                                  ).colorScheme.primary,
                                        ),
                                      ),
                                      title: FutureBuilder<String?>(
                                        future: _getContactNameFromNumber(
                                          item.number,
                                        ),
                                        builder: (context, snapshot) {
                                          String displayText = item.number;
                                          if (snapshot.connectionState ==
                                              ConnectionState.done) {
                                            displayText =
                                                snapshot.data?.isNotEmpty ==
                                                        true
                                                    ? snapshot.data!
                                                    : item.number;
                                          }
                                          return Text(
                                            displayText,
                                            style: TextStyle(
                                              fontFamily: tajawalFont,
                                              fontWeight: FontWeight.w600,
                                              color:
                                                  Theme.of(
                                                    context,
                                                  ).colorScheme.onSurface,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          );
                                        },
                                      ),
                                      subtitle: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          const SizedBox(height: 4),
                                          Text(
                                            '${_formatWithThousandsSeparator(item.amount)} ر.س',
                                            style: TextStyle(
                                              fontFamily: tajawalFont,
                                              fontWeight: FontWeight.bold,
                                              color:
                                                  Theme.of(
                                                    context,
                                                  ).colorScheme.primary,
                                            ),
                                          ),
                                          Text(
                                            convertNumberToArabicWords(
                                              item.amount,
                                            ),
                                            style: TextStyle(
                                              fontFamily: tajawalFont,
                                              color:
                                                  Theme.of(context)
                                                      .colorScheme
                                                      .onSurfaceVariant,
                                              fontSize: 12,
                                            ),
                                            maxLines: 1,
                                            overflow: TextOverflow.ellipsis,
                                          ),
                                        ],
                                      ),
                                      trailing: Row(
                                        mainAxisSize: MainAxisSize.min,
                                        children: [
                                          IconButton(
                                            icon: Icon(
                                              Icons.edit_outlined,
                                              color:
                                                  Theme.of(
                                                    context,
                                                  ).colorScheme.primary,
                                            ),
                                            onPressed:
                                                () => _editTransfer(index),
                                            tooltip: 'تعديل',
                                            padding: EdgeInsets.zero,
                                          ),
                                          IconButton(
                                            icon: Icon(
                                              Icons.delete_outline_rounded,
                                              color:
                                                  Theme.of(
                                                    context,
                                                  ).colorScheme.error,
                                            ),
                                            onPressed:
                                                () => _removeTransferAt(index),
                                            tooltip: 'حذف',
                                            padding: EdgeInsets.zero,
                                          ),
                                        ],
                                      ),
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
            ),
          ),
        ],
      ),
    );
  }

  void _removeTransferAt(int index) async {
    final removedNumber = _transferList[index].number;

    setState(() {
      _transferList.removeAt(index);
      // إزالة حالة التعديل الخاصة بهذا الرقم
      _amountEdited.remove(removedNumber);
    });
    await _saveTransferList();
  }

  void _editTransfer(int index) {
    var item = _transferList[index];
    int? selectedAmount = item.amount;
    final pinController = TextEditingController(text: item.pin ?? '');

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      backgroundColor: Theme.of(context).colorScheme.surface,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
      ),
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setModal) {
            return Directionality(
              textDirection: TextDirection.rtl,
              child: SingleChildScrollView(
                padding: EdgeInsets.only(
                  bottom: MediaQuery.of(context).viewInsets.bottom + 16,
                  top: 12,
                  left: 16,
                  right: 16,
                ),
                child: ConstrainedBox(
                  constraints: BoxConstraints(
                    maxHeight: MediaQuery.of(context).size.height * 0.85,
                  ),
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      // Header
                      Stack(
                        alignment: Alignment.center,
                        children: [
                          Align(
                            alignment: Alignment.centerLeft,
                            child: IconButton(
                              icon: Icon(
                                Icons.close_rounded,
                                size: 22,
                                color: Theme.of(context).colorScheme.onSurface,
                              ),
                              onPressed: () => Navigator.pop(context),
                              tooltip: 'إغلاق',
                              padding: EdgeInsets.zero,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 8),
                            child: Text(
                              "تغيير المبلغ",
                              style: Theme.of(
                                context,
                              ).textTheme.titleLarge?.copyWith(
                                fontWeight: FontWeight.bold,
                                fontFamily: tajawalFont,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),

                      ListTile(
                        contentPadding: EdgeInsets.zero,
                        leading: Container(
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: Theme.of(
                              context,
                            ).colorScheme.surfaceVariant.withOpacity(0.3),
                            shape: BoxShape.circle,
                          ),
                          child: Icon(
                            Icons.phone_rounded,
                            size: 20,
                            color: Theme.of(context).colorScheme.primary,
                          ),
                        ),
                        title: Text(
                          item.number,
                          textAlign: TextAlign.right,
                          style: Theme.of(
                            context,
                          ).textTheme.titleMedium?.copyWith(
                            fontFamily: tajawalFont,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        subtitle: Text(
                          'رقم الجوال',
                          textAlign: TextAlign.right,
                          style: Theme.of(
                            context,
                          ).textTheme.bodySmall?.copyWith(
                            fontFamily: tajawalFont,
                            color:
                                Theme.of(context).colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ),

                      const Divider(height: 24, thickness: 1),

                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 4),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'اختر المبلغ',
                              textAlign: TextAlign.right,
                              style: Theme.of(
                                context,
                              ).textTheme.titleMedium?.copyWith(
                                fontFamily: tajawalFont,
                                fontWeight: FontWeight.bold,
                                color: Theme.of(context).colorScheme.primary,
                              ),
                            ),
                            const SizedBox(height: 12),
                            SizedBox(
                              height: 160,
                              child: GridView.count(
                                physics: const NeverScrollableScrollPhysics(),
                                crossAxisCount: 3,
                                mainAxisSpacing: 8,
                                crossAxisSpacing: 8,
                                childAspectRatio: 1.6,
                                children:
                                    _savedAmounts.map((amt) {
                                      return GestureDetector(
                                        onTap:
                                            () => setModal(
                                              () => selectedAmount = amt,
                                            ),
                                        child: Container(
                                          decoration: BoxDecoration(
                                            color:
                                                selectedAmount == amt
                                                    ? Theme.of(context)
                                                        .colorScheme
                                                        .primary
                                                        .withOpacity(0.1)
                                                    : Theme.of(context)
                                                        .colorScheme
                                                        .surfaceVariant
                                                        .withOpacity(0.05),
                                            borderRadius: BorderRadius.circular(
                                              8,
                                            ),
                                            border: Border.all(
                                              color:
                                                  selectedAmount == amt
                                                      ? Theme.of(
                                                        context,
                                                      ).colorScheme.primary
                                                      : Theme.of(
                                                        context,
                                                      ).dividerColor,
                                              width: 1,
                                            ),
                                          ),
                                          child: Center(
                                            child: Column(
                                              mainAxisAlignment:
                                                  MainAxisAlignment.center,
                                              children: [
                                                Text(
                                                  _formatWithThousandsSeparator(
                                                    amt,
                                                  ),
                                                  style: TextStyle(
                                                    fontFamily: tajawalFont,
                                                    fontWeight: FontWeight.bold,
                                                    fontSize: 16,
                                                    color:
                                                        selectedAmount == amt
                                                            ? Theme.of(context)
                                                                .colorScheme
                                                                .primary
                                                            : Theme.of(context)
                                                                .colorScheme
                                                                .onSurface,
                                                  ),
                                                ),
                                                const SizedBox(height: 4),
                                                Text(
                                                  'ريال',
                                                  style: TextStyle(
                                                    fontFamily: tajawalFont,
                                                    fontSize: 12,
                                                    color:
                                                        selectedAmount == amt
                                                            ? Theme.of(context)
                                                                .colorScheme
                                                                .primary
                                                            : Theme.of(context)
                                                                .colorScheme
                                                                .onSurfaceVariant,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ),
                                        ),
                                      );
                                    }).toList(),
                              ),
                            ),
                          ],
                        ),
                      ),

                      const SizedBox(height: 16),

                      if (selectedAmount != null) ...[
                        Container(
                          padding: const EdgeInsets.all(12),
                          decoration: BoxDecoration(
                            color: Theme.of(
                              context,
                            ).colorScheme.primary.withOpacity(0.05),
                            borderRadius: BorderRadius.circular(8),
                            border: Border.all(
                              color: Theme.of(
                                context,
                              ).colorScheme.primary.withOpacity(0.2),
                              width: 1,
                            ),
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                            children: [
                              Text(
                                'المبلغ المحدد',
                                textAlign: TextAlign.right,
                                style: Theme.of(
                                  context,
                                ).textTheme.bodySmall?.copyWith(
                                  fontFamily: tajawalFont,
                                  color:
                                      Theme.of(
                                        context,
                                      ).colorScheme.onSurfaceVariant,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                '${_formatWithThousandsSeparator(selectedAmount!)} ريال',
                                textAlign: TextAlign.right,
                                style: Theme.of(
                                  context,
                                ).textTheme.titleLarge?.copyWith(
                                  fontFamily: tajawalFont,
                                  fontWeight: FontWeight.bold,
                                  color: Theme.of(context).colorScheme.primary,
                                ),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                convertNumberToArabicWords(selectedAmount!),
                                textAlign: TextAlign.right,
                                style: Theme.of(
                                  context,
                                ).textTheme.bodyMedium?.copyWith(
                                  fontFamily: tajawalFont,
                                  color:
                                      Theme.of(
                                        context,
                                      ).colorScheme.onSurfaceVariant,
                                ),
                              ),
                            ],
                          ),
                        ),
                        const SizedBox(height: 16),
                      ],

                      // Buttons
                      Row(
                        children: [
                          Expanded(
                            child: ElevatedButton(
                              onPressed: () async {
                                if (selectedAmount == null ||
                                    selectedAmount! <= 0) {
                                  _showSnackBar('يرجى اختيار مبلغ صحيح');
                                  return;
                                }
                                setState(() {
                                  _transferList[index].amount = selectedAmount!;
                                  _amountEdited[_transferList[index].number] =
                                      true;
                                });
                                await _saveTransferList();
                                Navigator.pop(context);
                              },
                              style: ElevatedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(
                                  vertical: 14,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                                backgroundColor:
                                    Theme.of(context).colorScheme.primary,
                              ),
                              child: const Text(
                                "تأكيد",
                                style: TextStyle(
                                  fontFamily: tajawalFont,
                                  fontWeight: FontWeight.w700,
                                  fontSize: 15,
                                ),
                              ),
                            ),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: OutlinedButton(
                              onPressed: () => Navigator.pop(context),
                              style: OutlinedButton.styleFrom(
                                padding: const EdgeInsets.symmetric(
                                  vertical: 14,
                                ),
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(12),
                                ),
                              ),
                              child: const Text(
                                "إلغاء",
                                style: TextStyle(
                                  fontFamily: tajawalFont,
                                  fontWeight: FontWeight.w600,
                                  fontSize: 15,
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            );
          },
        );
      },
    );
  }
}