اريد تحسين الدائرة الخاصة بجهه الاتصال التي بجوار الاسم
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:telephony/telephony.dart';
import 'package:flutter_contacts/flutter_contacts.dart';
import 'package:awesome_dialog/awesome_dialog.dart';

const backgroundColor = Color(0xFFF5F7FA);
const primaryColor = Color(0xFFFD7E35);
const accentColor = Color(0xFF2E3B4E);
const lightAccentColor = Color(0xFFFFF0E6);
const textColor = Color(0xFF2E3B4E);
const lightTextColor = Color(0xFF7F8FA4);
const cardColor = Colors.white;
const borderColor = Color(0xFFE5E9F2);
const secondaryColor = Color.fromARGB(255, 219, 102, 35);
const successColor = Color(0xFF4BB543);
const errorColor = Color(0xFFDC3545);
const tajawalFont = 'Tajawal';

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 SplashScreen extends StatefulWidget {
  const SplashScreen({super.key});

  @override
  State<SplashScreen> createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen>
    with TickerProviderStateMixin {
  bool _isLoading = true;
  bool _hasSavedBalance = false;
  bool _useSmsBalance = false;

  int _previousBalance = 0;
  int _currentBalance = 0;
  int _totalBalance = 0;
  int _savedPreviousBalance = 0;

  late TextEditingController _balanceController;
  final TextEditingController _searchController = TextEditingController();

  late AnimationController _animationController;
  late Animation<double> _logoScaleAnimation;
  late Animation<Offset> _contentSlideAnimation;
  late Animation<double> _fadeAnimation;

  final Telephony telephony = Telephony.instance;
  List<Contact> _contacts = [];
  List<Contact> _favoriteContacts = [];
  List<Contact> _filteredContacts = [];
  List<Contact> _filteredFavorites = [];

  @override
  void initState() {
    super.initState();
    _balanceController = TextEditingController();
    _balanceController.addListener(_updateBalance);
    _searchController.addListener(_updateSearchResults);

    _animationController = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 1000),
    );

    _logoScaleAnimation = Tween<double>(begin: 0.8, end: 1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOutBack),
    );
    _contentSlideAnimation = Tween<Offset>(
      begin: const Offset(0, 0.3),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeOutQuart),
    );
    _fadeAnimation = Tween<double>(begin: 0, end: 1).animate(
      CurvedAnimation(parent: _animationController, curve: Curves.easeInOut),
    );

    _animationController.forward();
    _loadBalance();
    _loadContacts();
  }

  @override
  void dispose() {
    _balanceController.removeListener(_updateBalance);
    _balanceController.dispose();
    _searchController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  void _updateBalance() {
    final input = _balanceController.text.replaceAll(',', '').trim();
    int currentInput = int.tryParse(input) ?? 0;
    setState(() {
      _previousBalance = _savedPreviousBalance;
      _currentBalance = currentInput;
      _totalBalance = _currentBalance - _previousBalance;
    });
  }

  void _updateSearchResults() {
    final query = _searchController.text.toLowerCase();
    setState(() {
      _filteredContacts =
          _contacts.where((contact) {
            final name = contact.displayName.toLowerCase();
            final phones = contact.phones.map((p) => p.number).join(' ');
            return name.contains(query) || phones.contains(query);
          }).toList();

      _filteredFavorites =
          _favoriteContacts.where((contact) {
            final name = contact.displayName.toLowerCase();
            final phones = contact.phones.map((p) => p.number).join(' ');
            return name.contains(query) || phones.contains(query);
          }).toList();
    });
  }

  Future<String?> _selectContact() async {
    final selectedNumbers = await showContactsSelection(
      context,
      _contacts,
      _favoriteContacts,
    );

    if (selectedNumbers.isNotEmpty) {
      return selectedNumbers.first;
    }
    return null;
  }

  Future<void> _loadContacts() async {
    bool permissionGranted = await FlutterContacts.requestPermission();
    if (!permissionGranted) {
      if (mounted) {
        _showErrorDialog(
          'السماح مطلوب',
          'يرجى السماح بالوصول إلى جهات الاتصال',
        );
      }
      return;
    }
    final contacts = await FlutterContacts.getContacts(withProperties: true);
    if (mounted) {
      setState(() {
        _contacts =
            contacts.where((contact) => contact.phones.isNotEmpty).toList();
        _favoriteContacts = _contacts.take(3).toList();
        _filteredContacts = List.from(_contacts);
        _filteredFavorites = List.from(_favoriteContacts);
      });
    }
  }

  // دالة لعرض صفحة جهات الاتصال المفضلة
  Future<List<String>> showContactsSelection(
    BuildContext context,
    List<Contact> contacts,
    List<Contact> favoriteContacts,
  ) async {
    List<String> selectedNumbers = [];
    final searchController = TextEditingController();
    String searchQuery = '';

    // دالة لتصفية جهات الاتصال
    List<Contact> _filterContacts(List<Contact> contacts, String query) {
      if (query.isEmpty) return contacts;
      return contacts.where((contact) {
        final name = contact.displayName.toLowerCase();
        final phones = contact.phones.map((p) => p.number).join(' ');
        return name.contains(query.toLowerCase()) ||
            phones.contains(query.toLowerCase());
      }).toList();
    }

    // واجهة فارغة عند عدم وجود نتائج
    Widget _buildEmptyState(BuildContext context) {
      return Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              Icons.contacts_outlined,
              size: 60,
              color: Theme.of(context).colorScheme.onSurface.withOpacity(0.3),
            ),
            const SizedBox(height: 16),
            Text(
              'لا توجد جهات اتصال',
              style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                color: Theme.of(context).colorScheme.onSurface.withOpacity(0.5),
                fontFamily: tajawalFont,
              ),
            ),
          ],
        ),
      );
    }

    // بناء قائمة جهات الاتصال
    Widget _buildContactsList(
      BuildContext context,
      List<Contact> contacts,
      List<String> selectedNumbers,
      StateSetter setModal,
    ) {
      return ListView.builder(
        itemCount: contacts.length,
        itemBuilder: (context, index) {
          final contact = contacts[index];
          final isSelected =
              selectedNumbers.isNotEmpty &&
              contact.phones.isNotEmpty &&
              selectedNumbers.first == contact.phones.first.number;
          final isFavorite = favoriteContacts.any((c) => c.id == contact.id);

          return Column(
            children: [
              ListTile(
                leading: CircleAvatar(
                  backgroundColor:
                      isFavorite
                          ? Colors.amber.withOpacity(0.2)
                          : Theme.of(
                            context,
                          ).colorScheme.primary.withOpacity(0.1),
                ),
                title: Text(
                  contact.displayName,
                  style: Theme.of(
                    context,
                  ).textTheme.bodyLarge?.copyWith(fontFamily: tajawalFont),
                ),
                subtitle:
                    contact.phones.isNotEmpty
                        ? Text(
                          contact.phones.first.number,
                          style: Theme.of(context).textTheme.bodySmall
                              ?.copyWith(fontFamily: tajawalFont),
                        )
                        : null,
                trailing: Container(
                  width: 28,
                  height: 28,
                  decoration: BoxDecoration(
                    shape: BoxShape.circle,
                    border: Border.all(
                      color: isSelected ? primaryColor : Colors.grey,
                      width: 2,
                    ),
                    color: isSelected ? primaryColor : Colors.transparent,
                  ),
                  child:
                      isSelected
                          ? const Icon(
                            Icons.check,
                            color: Colors.white,
                            size: 18,
                          )
                          : null,
                ),
                onTap: () {
                  setModal(() {
                    if (contact.phones.isNotEmpty) {
                      final phoneNumber = contact.phones.first.number;
                      if (selectedNumbers.contains(phoneNumber)) {
                        selectedNumbers.clear();
                      } else {
                        selectedNumbers.clear();
                        selectedNumbers.add(phoneNumber);
                      }
                    }
                  });
                },
              ),
              const Divider(height: 1, thickness: 0.5),
            ],
          );
        },
      );
    }

    // أزرار القاع
    Widget _buildBottomButtons(
      BuildContext context,
      List<String> selectedNumbers,
      StateSetter setModal,
    ) {
      return Padding(
        padding: const EdgeInsets.all(16),
        child: Row(
          children: [
            Expanded(
              child: OutlinedButton(
                onPressed: () => Navigator.pop(context),
                style: OutlinedButton.styleFrom(
                  padding: const EdgeInsets.symmetric(vertical: 16),
                  side: BorderSide(
                    color: Theme.of(context).colorScheme.primary,
                  ),
                ),
                child: Text(
                  'إلغاء',
                  style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                    color: Theme.of(context).colorScheme.primary,
                    fontFamily: tajawalFont,
                  ),
                ),
              ),
            ),
            const SizedBox(width: 16),
            Expanded(
              child: ElevatedButton(
                onPressed:
                    selectedNumbers.isEmpty
                        ? null
                        : () => Navigator.pop(context, selectedNumbers),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  padding: const EdgeInsets.symmetric(vertical: 16),
                ),
                child: Text(
                  'إضافة (${selectedNumbers.length})',
                  style: Theme.of(context).textTheme.bodyLarge?.copyWith(
                    color: Colors.white,
                    fontFamily: tajawalFont,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    }

    return await showModalBottomSheet<List<String>>(
          context: context,
          isScrollControlled: true,
          backgroundColor: Colors.transparent,
          builder: (context) {
            return Directionality(
              textDirection: TextDirection.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(
                            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),
                                  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(
                            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),
                      ],
                    ),
                  );
                },
              ),
            );
          },
        ) ??
        []; // return empty list if null
  }

  void _toggleFavorite(Contact contact, bool isCurrentlyFavorite) {
    setState(() {
      if (isCurrentlyFavorite) {
        _favoriteContacts.remove(contact);
      } else {
        _favoriteContacts.add(contact);
      }
      _updateSearchResults();
    });
  }

  Widget _buildContactItem(
    Contact contact,
    bool isFavorite,
    VoidCallback onTap,
    VoidCallback onFavoriteToggle,
  ) {
    return InkWell(
      onTap: onTap,
      child: Container(
        margin: const EdgeInsets.only(bottom: 8),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(12),
          boxShadow: [
            BoxShadow(
              color: Colors.black.withOpacity(0.05),
              blurRadius: 6,
              offset: const Offset(0, 2),
            ),
          ],
        ),
        child: ListTile(
          leading: Container(
            width: 40,
            height: 40,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors:
                    isFavorite
                        ? [Colors.amber, Colors.orange]
                        : [
                          primaryColor.withOpacity(0.2),
                          secondaryColor.withOpacity(0.2),
                        ],
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
              ),
              shape: BoxShape.circle,
            ),
          ),
          title: Text(
            contact.displayName,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: textColor,
              fontFamily: tajawalFont,
            ),
          ),
          subtitle:
              contact.phones.isNotEmpty
                  ? Text(
                    contact.phones.first.number,
                    style: TextStyle(
                      color: lightTextColor,
                      fontFamily: tajawalFont,
                    ),
                  )
                  : null,
          trailing: IconButton(
            icon: Icon(
              isFavorite ? Icons.star : Icons.star_border,
              color: isFavorite ? Colors.amber : Colors.grey[400],
            ),
            onPressed: onFavoriteToggle,
          ),
          contentPadding: const EdgeInsets.symmetric(
            horizontal: 16,
            vertical: 8,
          ),
        ),
      ),
    );
  }

  Future<bool> _requestPermissions() async {
    PermissionStatus smsStatus = await Permission.sms.status;
    if (!smsStatus.isGranted) {
      smsStatus = await Permission.sms.request();
    }
    return smsStatus.isGranted;
  }

  Future<String?> _getLatestSmsFromNumber(String senderNumber) async {
    bool? permissionsGranted = await telephony.requestSmsPermissions;
    if (permissionsGranted != true) return null;

    String formatNumber(String number) {
      return number.replaceAll(RegExp(r'[^0-9]'), '');
    }

    String formattedSenderNumber = formatNumber(senderNumber);

    final List<SmsMessage> messages = await telephony.getInboxSms(
      columns: [SmsColumn.ADDRESS, SmsColumn.BODY],
      filter: SmsFilter.where(
        SmsColumn.ADDRESS,
      ).like('%$formattedSenderNumber%'),
      sortOrder: [OrderBy(SmsColumn.DATE_SENT, sort: Sort.DESC)],
    );

    return messages.isNotEmpty ? messages.first.body : null;
  }

  double? extractBalanceFromMessage(String message) {
    RegExp regex = RegExp(r'(\d{1,3}(,\d{3})*(\.\d+)?|\d+(\.\d+)?)');
    final matches = regex.allMatches(message);
    double? maxValue;

    for (var match in matches) {
      final valueStr = match.group(0)?.replaceAll(',', '');
      if (valueStr != null) {
        final val = double.tryParse(valueStr);
        if (val != null && (maxValue == null || val > maxValue)) {
          maxValue = val;
        }
      }
    }
    return maxValue;
  }

  String _formatDoubleWithThousandsSeparator(double value) {
    String fixed = value.toStringAsFixed(2);
    final parts = fixed.split('.');
    String integerPart = parts[0];
    final buffer = StringBuffer();

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

    return parts[1] == '00'
        ? buffer.toString()
        : '${buffer.toString()}.${parts[1]}';
  }

  Future<void> _fetchBalanceFromSms() async {
    bool havePermissions = await _requestPermissions();
    if (!havePermissions) {
      _showErrorDialog('صلاحية مطلوبة', 'يرجى السماح بصلاحيات قراءة الرسائل');
      return;
    }

    final senderNumber = await _selectContact();
    if (senderNumber == null || senderNumber.isEmpty) {
      _showErrorDialog('خطأ', 'لم يتم إدخال رقم جهة اتصال');
      return;
    }

    String? smsText = await _getLatestSmsFromNumber(senderNumber);
    if (smsText == null) {
      _showErrorDialog('خطأ', 'لم يتم العثور على رسائل من جهة الاتصال');
      return;
    }

    double? balance = extractBalanceFromMessage(smsText);
    if (balance != null) {
      setState(() {
        _balanceController.text =
            _formatDoubleWithThousandsSeparator(balance).split('.').first;
        _useSmsBalance = true;
      });
      _showSuccessDialog('نجاح', 'تم جلب الرصيد من رسالة جهة الاتصال');
    } else {
      _showErrorDialog('خطأ', 'لم يتم العثور على رصيد صالح في الرسالة');
    }
  }

  void _showSuccessDialog(String title, String message) {
    AwesomeDialog(
      context: context,
      dialogType: DialogType.success,
      animType: AnimType.scale,
      title: title,
      desc: message,
      titleTextStyle: TextStyle(
        fontSize: 20,
        fontWeight: FontWeight.bold,
        color: textColor,
        fontFamily: tajawalFont,
      ),
      descTextStyle: TextStyle(
        fontSize: 16,
        color: lightTextColor,
        fontFamily: tajawalFont,
      ),
      btnOkText: 'حسناً',
      btnOkColor: primaryColor,
      btnOkOnPress: () {},
    ).show();
  }

  void _showErrorDialog(String title, String message) {
    AwesomeDialog(
      context: context,
      dialogType: DialogType.error,
      animType: AnimType.scale,
      title: title,
      desc: message,
      titleTextStyle: TextStyle(
        fontSize: 20,
        fontWeight: FontWeight.bold,
        color: textColor,
        fontFamily: tajawalFont,
      ),
      descTextStyle: TextStyle(
        fontSize: 16,
        color: lightTextColor,
        fontFamily: tajawalFont,
      ),
      btnOkText: 'حسناً',
      btnOkColor: primaryColor,
      btnOkOnPress: () {},
    ).show();
  }

  String _formatWithThousandsSeparator(int value) {
    return value.toString().replaceAllMapped(
      RegExp(r'(\d)(?=(\d{3})+(?!\d))'),
      (Match m) => '${m[1]},',
    );
  }

  Future<void> _loadBalance() async {
    final prefs = await SharedPreferences.getInstance();
    final savedData = prefs.getString('balance_data');

    if (savedData != null) {
      final Map<String, dynamic> jsonData = jsonDecode(savedData);
      _savedPreviousBalance = jsonData['previous_balance'] ?? 0;

      setState(() {
        _previousBalance = _savedPreviousBalance;
        _currentBalance = jsonData['current_balance'] ?? 0;
        _totalBalance = jsonData['total_balance'] ?? _currentBalance;
        _hasSavedBalance = true;
        _balanceController.text = _formatWithThousandsSeparator(
          _currentBalance,
        );
      });
    } else {
      setState(() => _hasSavedBalance = false);
    }
    setState(() => _isLoading = false);
  }

  Future<void> _saveBalances({
    required int previousBalance,
    required int currentBalance,
    required int totalBalance,
  }) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(
      'balance_data',
      jsonEncode({
        'previous_balance': previousBalance,
        'current_balance': currentBalance,
        'total_balance': totalBalance,
      }),
    );
  }

  void _onContinue() async {
    final currentInput = _balanceController.text.replaceAll(',', '').trim();
    final currentBalanceInput = int.tryParse(currentInput);

    if (currentBalanceInput == null || currentBalanceInput <= 0) {
      _showErrorDialog(
        'خطأ في الإدخال',
        'يرجى إدخال مبلغ رصيد صالح (أكبر من صفر)',
      );
      return;
    }

    setState(() {
      _previousBalance = _currentBalance;
      _savedPreviousBalance = _previousBalance;
      _currentBalance = currentBalanceInput!;
      _totalBalance = _currentBalance - _previousBalance;
      _hasSavedBalance = true;
    });

    await _saveBalances(
      previousBalance: _savedPreviousBalance,
      currentBalance: _currentBalance,
      totalBalance: _totalBalance,
    );

    Navigator.pushReplacementNamed(context, '/home');
  }

  Widget _smallBalanceInfo(String label, int value) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      decoration: BoxDecoration(
        color: cardColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Text(
            label,
            style: TextStyle(
              fontFamily: tajawalFont,
              color: lightTextColor,
              fontSize: 12,
            ),
          ),
          const SizedBox(height: 6),
          Text(
            _formatWithThousandsSeparator(value),
            style: TextStyle(
              fontFamily: tajawalFont,
              fontWeight: FontWeight.bold,
              color: primaryColor,
              fontSize: 16,
            ),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    return Scaffold(
      backgroundColor: backgroundColor,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(
            horizontal: MediaQuery.of(context).size.width * 0.05,
            vertical: 16,
          ),
          child:
              _isLoading
                  ? Center(
                    child: CircularProgressIndicator(
                      color: accentColor,
                      strokeWidth: 2,
                    ),
                  )
                  : Column(
                    children: [
                      Expanded(
                        child: CustomScrollView(
                          physics: const BouncingScrollPhysics(),
                          slivers: [
                            SliverToBoxAdapter(
                              child: Column(
                                children: [
                                  const SizedBox(height: 20),
                                  _buildAppLogo(),
                                  const SizedBox(height: 30),
                                  _buildWelcomeSection(),
                                  const SizedBox(height: 40),
                                  _buildBalanceInputSection(),
                                ],
                              ),
                            ),
                            if (_hasSavedBalance)
                              SliverToBoxAdapter(
                                child: Column(
                                  children: [
                                    const SizedBox(height: 30),
                                    _buildBalanceSummary(),
                                    const SizedBox(height: 20),
                                  ],
                                ),
                              ),
                            const SliverFillRemaining(
                              hasScrollBody: false,
                              child: SizedBox(height: 20),
                            ),
                          ],
                        ),
                      ),
                      _buildContinueButton(),
                    ],
                  ),
        ),
      ),
    );
  }

  Widget _buildAppLogo() {
    return Container(
      width: 120,
      height: 120,
      decoration: BoxDecoration(
        gradient: const LinearGradient(
          colors: [primaryColor, secondaryColor],
          begin: Alignment.topLeft,
          end: Alignment.bottomRight,
        ),
        shape: BoxShape.circle,
        boxShadow: [
          BoxShadow(
            color: primaryColor.withOpacity(0.2),
            blurRadius: 20,
            spreadRadius: 5,
          ),
        ],
      ),
      child: Stack(
        alignment: Alignment.center,
        children: [
          const Icon(Icons.swap_horiz_rounded, size: 50, color: Colors.white),
          Positioned(
            right: 10,
            bottom: 10,
            child: Container(
              padding: const EdgeInsets.all(6),
              decoration: BoxDecoration(
                color: accentColor,
                shape: BoxShape.circle,
                border: Border.all(color: Colors.white, width: 2),
              ),
              child: const Icon(Icons.bolt, size: 16, color: Colors.white),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildWelcomeSection() {
    return Column(
      children: [
        Text(
          'مرحبًا بك في حوّلها فايبرافون',
          style: TextStyle(
            fontSize: 24,
            fontWeight: FontWeight.bold,
            color: textColor,
            fontFamily: tajawalFont,
          ),
        ),
        const SizedBox(height: 12),
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 20),
          child: Text(
            'أدخل رصيدك الحالي لبدء رحلة تحويل الأموال بسهولة وأمان',
            style: TextStyle(
              fontSize: 14,
              color: lightTextColor,
              fontFamily: tajawalFont,
              height: 1.6,
            ),
            textAlign: TextAlign.center,
          ),
        ),
      ],
    );
  }

  Widget _buildBalanceInputSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.end,
      children: [
        Text(
          'طريقة إدخال الرصيد',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: textColor,
            fontFamily: tajawalFont,
          ),
        ),
        const SizedBox(height: 12),
        Container(
          decoration: BoxDecoration(
            color: cardColor,
            borderRadius: BorderRadius.circular(12),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 10,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child: Column(
            children: [
              _buildInputMethodToggle(),
              if (!_useSmsBalance) _buildManualInputField(),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildInputMethodToggle() {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Row(
        children: [
          Expanded(
            child: InkWell(
              onTap: () => setState(() => _useSmsBalance = false),
              borderRadius: BorderRadius.circular(8),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 14),
                decoration: BoxDecoration(
                  color:
                      !_useSmsBalance
                          ? primaryColor.withOpacity(0.1)
                          : Colors.transparent,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: !_useSmsBalance ? primaryColor : Colors.transparent,
                    width: 1.5,
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.edit,
                      color: !_useSmsBalance ? primaryColor : lightTextColor,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      'إدخال يدوي',
                      style: TextStyle(
                        color: !_useSmsBalance ? primaryColor : lightTextColor,
                        fontWeight: FontWeight.bold,
                        fontFamily: tajawalFont,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          const SizedBox(width: 10),
          Expanded(
            child: InkWell(
              onTap: () {
                setState(() => _useSmsBalance = true);
                _fetchBalanceFromSms();
              },
              borderRadius: BorderRadius.circular(8),
              child: Container(
                padding: const EdgeInsets.symmetric(vertical: 14),
                decoration: BoxDecoration(
                  color:
                      _useSmsBalance
                          ? primaryColor.withOpacity(0.1)
                          : Colors.transparent,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: _useSmsBalance ? primaryColor : Colors.transparent,
                    width: 1.5,
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Icon(
                      Icons.sms,
                      color: _useSmsBalance ? primaryColor : lightTextColor,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      'جلب من رسالة',
                      style: TextStyle(
                        color: _useSmsBalance ? primaryColor : lightTextColor,
                        fontWeight: FontWeight.bold,
                        fontFamily: tajawalFont,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildManualInputField() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: TextField(
        controller: _balanceController,
        keyboardType: TextInputType.number,
        inputFormatters: [ThousandsSeparatorInputFormatter()],
        textAlign: TextAlign.right,
        style: TextStyle(
          fontSize: 18,
          fontWeight: FontWeight.bold,
          color: textColor,
          fontFamily: tajawalFont,
        ),
        decoration: InputDecoration(
          filled: true,
          fillColor: backgroundColor,
          hintText: 'أدخل الرصيد الحالي',
          hintStyle: TextStyle(color: lightTextColor, fontFamily: tajawalFont),
          prefixIcon: Padding(
            padding: const EdgeInsets.only(left: 16, right: 8),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(Icons.attach_money, color: primaryColor),
                Container(
                  width: 1,
                  height: 20,
                  margin: const EdgeInsets.symmetric(horizontal: 8),
                  color: Colors.grey[300],
                ),
              ],
            ),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(12),
            borderSide: BorderSide.none,
          ),
          contentPadding: const EdgeInsets.symmetric(
            vertical: 16,
            horizontal: 20,
          ),
        ),
      ),
    );
  }

  Widget _buildBalanceSummary() {
    return Column(
      children: [
        Text(
          'ملخص الرصيد',
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: textColor,
            fontFamily: tajawalFont,
          ),
        ),
        const SizedBox(height: 16),
        LayoutBuilder(
          builder: (context, constraints) {
            final isSmallScreen = constraints.maxWidth < 400;
            return isSmallScreen
                ? Column(
                  children: [
                    _buildBalanceInfoCard('الرصيد السابق', _previousBalance),
                    const SizedBox(height: 10),
                    _buildBalanceInfoCard('الرصيد الحالي', _currentBalance),
                    const SizedBox(height: 10),
                    _buildBalanceInfoCard('الرصيد المُودَع', _totalBalance),
                  ],
                )
                : Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    Flexible(
                      child: _buildBalanceInfoCard(
                        'الرصيد السابق',
                        _previousBalance,
                      ),
                    ),
                    Flexible(
                      child: _buildBalanceInfoCard(
                        'الرصيد الحالي',
                        _currentBalance,
                      ),
                    ),
                    Flexible(
                      child: _buildBalanceInfoCard(
                        'الرصيد المُودَع',
                        _totalBalance,
                      ),
                    ),
                  ],
                );
          },
        ),
      ],
    );
  }

  Widget _buildBalanceInfoCard(String title, int value) {
    return Container(
      padding: const EdgeInsets.symmetric(vertical: 16, horizontal: 12),
      margin: const EdgeInsets.symmetric(horizontal: 4),
      decoration: BoxDecoration(
        color: cardColor,
        borderRadius: BorderRadius.circular(12),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 8,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Icon(
                _getBalanceIcon(title),
                color: _getBalanceColor(title),
                size: 18,
              ),
              const SizedBox(width: 6),
              Text(
                title,
                style: TextStyle(
                  fontSize: 12,
                  color: lightTextColor,
                  fontFamily: tajawalFont,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          FittedBox(
            child: Text(
              _formatWithThousandsSeparator(value),
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: textColor,
                fontFamily: tajawalFont,
              ),
            ),
          ),
        ],
      ),
    );
  }

  IconData _getBalanceIcon(String title) {
    switch (title) {
      case 'الرصيد السابق':
        return Icons.history;
      case 'الرصيد الحالي':
        return Icons.account_balance_wallet;
      case 'الرصيد المُودَع':
        return Icons.add_circle;
      default:
        return Icons.info;
    }
  }

  Color _getBalanceColor(String title) {
    switch (title) {
      case 'الرصيد السابق':
        return lightTextColor;
      case 'الرصيد الحالي':
        return primaryColor;
      case 'الرصيد المُودَع':
        return _totalBalance >= 0 ? successColor : errorColor;
      default:
        return lightTextColor;
    }
  }

  Widget _buildContinueButton() {
    return Padding(
      padding: const EdgeInsets.only(bottom: 20),
      child: SizedBox(
        width: double.infinity,
        child: ElevatedButton(
          onPressed: _onContinue,
          style: ElevatedButton.styleFrom(
            backgroundColor: primaryColor,
            foregroundColor: Colors.white,
            padding: const EdgeInsets.symmetric(vertical: 18),
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(12),
            ),
            elevation: 0,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min, // لتفادي اخطاء overflow
            children: [
              Flexible(
                child: Text(
                  'ابدأ الآن',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                    fontFamily: tajawalFont,
                  ),
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              const SizedBox(width: 8),
              const Icon(Icons.arrow_forward, size: 20),
            ],
          ),
        ),
      ),
    );
  }
}