/// Payment QR Page
///
/// QR code payment screen with bank transfer information.
/// Features:
/// - QR code for quick payment
/// - Bank transfer information with copy buttons
/// - Payment confirmation and proof upload buttons
/// - Countdown timer for payment
/// - Payment instructions modal
library;

import 'dart:async';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:go_router/go_router.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:image_picker/image_picker.dart';
import 'package:qr_flutter/qr_flutter.dart';

import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/features/orders/presentation/providers/order_repository_provider.dart';

/// Payment QR Page
///
/// Displays QR code and bank transfer information for payment.
class PaymentQrPage extends HookConsumerWidget {
  final String orderId;

  const PaymentQrPage({
    super.key,
    required this.orderId,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final colorScheme = Theme.of(context).colorScheme;

    // QR code data state
    final qrCodeData = useState<Map<String, dynamic>?>(null);
    final isLoadingQr = useState<bool>(true);
    final qrError = useState<String?>(null);

    // Countdown timer (15 minutes = 900 seconds)
    final remainingSeconds = useState<int>(900);
    final timer = useRef<Timer?>(null);

    // Upload state
    final isUploadingBill = useState<bool>(false);
    final selectedImagePath = useState<String?>(null);

    // Fetch QR code data
    useEffect(() {
      Future<void> fetchQrCode() async {
        try {
          isLoadingQr.value = true;
          qrError.value = null;
          final repository = await ref.read(orderRepositoryProvider.future);
          final data = await repository.generateQrCode(orderId);
          qrCodeData.value = data;
        } catch (e) {
          qrError.value = e.toString();
        } finally {
          isLoadingQr.value = false;
        }
      }

      fetchQrCode();
      return null;
    }, [orderId]);

    // Start countdown timer
    useEffect(() {
      timer.value = Timer.periodic(const Duration(seconds: 1), (t) {
        if (remainingSeconds.value > 0) {
          remainingSeconds.value--;
        } else {
          t.cancel();
        }
      });

      return () {
        timer.value?.cancel();
      };
    }, []);

    // Format timer display
    final minutes = remainingSeconds.value ~/ 60;
    final seconds = remainingSeconds.value % 60;
    final timerDisplay =
        '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';

    return Scaffold(
      backgroundColor: colorScheme.surfaceContainerLowest,
      appBar: AppBar(
        backgroundColor: colorScheme.surface,
        elevation: 0,
        leading: IconButton(
          icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
          onPressed: () => context.pop(),
        ),
        title: Text(
          'Thanh toán',
          style: TextStyle(
            color: colorScheme.onSurface,
            fontSize: 18,
            fontWeight: FontWeight.bold,
          ),
        ),
        centerTitle: false,
        actions: [
          IconButton(
            icon: FaIcon(FontAwesomeIcons.circleInfo, color: colorScheme.onSurface, size: 20),
            onPressed: () => _showInfoDialog(context),
          ),
          const SizedBox(width: AppSpacing.sm),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: AppSpacing.md),

            // QR Code Card
            _buildQrCodeCard(
              context,
              orderId,
              qrCodeData.value?['qr_code'] as String?,
              isLoadingQr.value,
            ),

            const SizedBox(height: AppSpacing.md),

            // Bank Transfer Info Card
            _buildBankInfoCard(
              context,
              orderId,
              qrCodeData.value?['bank_info']?['bank_name'] as String?,
              qrCodeData.value?['bank_info']?['account_no'] as String?,
              qrCodeData.value?['bank_info']?['account_name'] as String?,
              isLoadingQr.value,
            ),

            const SizedBox(height: AppSpacing.md),

            // Image Preview Section
            _buildImagePreviewSection(
              context,
              selectedImagePath.value,
              () async {
                await _selectImage(context, selectedImagePath);
              },
            ),

            const SizedBox(height: AppSpacing.md),

            // Action Buttons
            _buildActionButtons(
              context,
              ref,
              isUploadingBill.value,
              selectedImagePath.value != null,
              () async {
                await _uploadBill(context, ref, selectedImagePath, isUploadingBill);
              },
            ),

            const SizedBox(height: AppSpacing.md),

            // Timer
            _buildTimer(context, timerDisplay, remainingSeconds.value),

            const SizedBox(height: AppSpacing.lg),
          ],
        ),
      ),
    );
  }

  /// Build QR code card
  Widget _buildQrCodeCard(
    BuildContext context,
    String orderId,
    String? qrCodeData,
    bool isLoading,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: colorScheme.onSurface.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        children: [
          Text(
            'Quét mã QR để thanh toán',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: AppSpacing.md),
          Container(
            width: 220,
            height: 220,
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: colorScheme.surface,
              borderRadius: BorderRadius.circular(AppRadius.card),
              border: Border.all(color: colorScheme.outlineVariant),
            ),
            child: isLoading
                ? const CustomLoadingIndicator()
                : qrCodeData != null && qrCodeData.isNotEmpty
                    ? QrImageView(
                        data: qrCodeData,
                        version: QrVersions.auto,
                        size: 200.0,
                        backgroundColor: colorScheme.surface,
                        errorCorrectionLevel: QrErrorCorrectLevel.M,
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          FaIcon(FontAwesomeIcons.qrcode, size: 80, color: colorScheme.onSurfaceVariant),
                          const SizedBox(height: 8),
                          Text(
                            'Không thể tải mã QR',
                            style: TextStyle(fontSize: 12, color: colorScheme.onSurfaceVariant),
                          ),
                        ],
                      ),
          ),
          const SizedBox(height: AppSpacing.md),
          Text(
            'Quét mã QR bằng ứng dụng ngân hàng để thanh toán nhanh chóng',
            textAlign: TextAlign.center,
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
          ),
        ],
      ),
    );
  }

  /// Build bank transfer info card
  Widget _buildBankInfoCard(
    BuildContext context,
    String orderId,
    String? bankName,
    String? accountNo,
    String? accountName,
    bool isLoading,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: colorScheme.onSurface.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Thông tin chuyển khoản',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: AppSpacing.md),

          // Bank Name
          _buildInfoRow(
            context: context,
            label: 'Ngân hàng:',
            value: bankName ?? 'BIDV',
          ),

          const Divider(height: 24),

          // Account Number
          _buildInfoRow(
            context: context,
            label: 'Số tài khoản:',
            value: accountNo ?? '19036810704016',
          ),

          const Divider(height: 24),

          // Account Holder
          _buildInfoRow(
            context: context,
            label: 'Chủ tài khoản:',
            value: accountName ?? 'CÔNG TY EUROTILE',
          ),

          const Divider(height: 24),

          // Transfer Content
          _buildInfoRow(
            context: context,
            label: 'Nội dung:',
            value: orderId,
          ),

          const SizedBox(height: AppSpacing.md),

          // Note
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: colorScheme.primary.withValues(alpha: 0.1),
              borderRadius: BorderRadius.circular(AppRadius.card),
              border: Border.all(color: colorScheme.primary.withValues(alpha: 0.3)),
            ),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                FaIcon(
                  FontAwesomeIcons.lightbulb,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Expanded(
                  child: RichText(
                    text: TextSpan(
                      style: TextStyle(
                        fontSize: 13,
                        color: colorScheme.primary,
                        height: 1.4,
                      ),
                      children: [
                        const TextSpan(
                          text: 'Lưu ý: ',
                          style: TextStyle(fontWeight: FontWeight.bold),
                        ),
                        const TextSpan(
                          text:
                              'Vui lòng ghi đúng nội dung chuyển khoản để đơn hàng được xử lý nhanh chóng.',
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// Build info row with copy button
  Widget _buildInfoRow({
    required BuildContext context,
    required String label,
    required String value,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return Row(
      children: [
        Expanded(
          flex: 2,
          child: Text(
            label,
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
          ),
        ),
        Expanded(
          flex: 3,
          child: Text(
            value,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
        ),
        IconButton(
          icon: FaIcon(FontAwesomeIcons.copy, size: 18, color: colorScheme.primary),
          onPressed: () => _copyToClipboard(context, value),
          padding: EdgeInsets.zero,
          constraints: const BoxConstraints(),
        ),
      ],
    );
  }

  /// Build image preview section
  Widget _buildImagePreviewSection(
    BuildContext context,
    String? imagePath,
    VoidCallback onSelectImage,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: colorScheme.onSurface.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Ảnh hóa đơn',
            style: TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
              color: colorScheme.onSurface,
            ),
          ),
          const SizedBox(height: AppSpacing.md),

          // Image preview or placeholder
          InkWell(
            onTap: onSelectImage,
            borderRadius: BorderRadius.circular(AppRadius.card),
            child: Container(
              width: double.infinity,
              height: 200,
              decoration: BoxDecoration(
                color: colorScheme.surfaceContainerLowest,
                borderRadius: BorderRadius.circular(AppRadius.card),
                border: Border.all(
                  color: colorScheme.outlineVariant,
                  width: 2,
                  style: BorderStyle.solid,
                ),
              ),
              child: imagePath != null
                  ? ClipRRect(
                      borderRadius: BorderRadius.circular(AppRadius.card - 2),
                      child: Stack(
                        children: [
                          Image.file(
                            File(imagePath),
                            width: double.infinity,
                            height: double.infinity,
                            fit: BoxFit.cover,
                          ),
                          Positioned(
                            top: 8,
                            right: 8,
                            child: Container(
                              decoration: BoxDecoration(
                                color: colorScheme.onSurface.withValues(alpha: 0.6),
                                borderRadius: BorderRadius.circular(20),
                              ),
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              child: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: [
                                  FaIcon(
                                    FontAwesomeIcons.pen,
                                    color: colorScheme.surface,
                                    size: 12,
                                  ),
                                  const SizedBox(width: 6),
                                  Text(
                                    'Đổi ảnh',
                                    style: TextStyle(
                                      color: colorScheme.surface,
                                      fontSize: 12,
                                      fontWeight: FontWeight.w500,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    )
                  : Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                          width: 60,
                          height: 60,
                          decoration: BoxDecoration(
                            color: colorScheme.primary.withValues(alpha: 0.1),
                            borderRadius: BorderRadius.circular(30),
                          ),
                          child: Icon(
                            FontAwesomeIcons.image,
                            color: colorScheme.primary,
                            size: 24,
                          ),
                        ),
                        const SizedBox(height: 12),
                        Text(
                          'Chạm để chọn ảnh hóa đơn',
                          style: TextStyle(
                            fontSize: 14,
                            color: colorScheme.onSurfaceVariant,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          'Hỗ trợ: JPG, PNG',
                          style: TextStyle(
                            fontSize: 12,
                            color: colorScheme.onSurfaceVariant,
                          ),
                        ),
                      ],
                    ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build action buttons
  Widget _buildActionButtons(
    BuildContext context,
    WidgetRef ref,
    bool isUploading,
    bool hasImage,
    VoidCallback onUpload,
  ) {
    final colorScheme = Theme.of(context).colorScheme;

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      child: Column(
        children: [
          // Upload Bill Button
          SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: (isUploading || !hasImage) ? null : onUpload,
              icon: isUploading
                  ? SizedBox(
                      width: 18,
                      height: 18,
                      child: CustomLoadingIndicator(color: colorScheme.primary, size: 20),
                    )
                  : const FaIcon(FontAwesomeIcons.camera, size: 18),
              label: Text(
                isUploading ? 'Đang upload...' : 'Upload bill chuyển khoản',
                style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
              ),
              style: ElevatedButton.styleFrom(
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                padding: const EdgeInsets.symmetric(vertical: 14),
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
                disabledBackgroundColor: colorScheme.surfaceContainerLowest,
                disabledForegroundColor: colorScheme.onSurfaceVariant,
              ),
            ),
          ),
          const SizedBox(height: AppSpacing.sm),

          // Back to Home Button
          SizedBox(
            width: double.infinity,
            child: OutlinedButton.icon(
              onPressed: isUploading ? null : () => context.goNamed(RouteNames.home),
              icon: const FaIcon(FontAwesomeIcons.house, size: 18),
              label: const Text(
                'Quay về trang chủ',
                style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
              ),
              style: OutlinedButton.styleFrom(
                foregroundColor: colorScheme.onSurface,
                side: BorderSide(
                  color: colorScheme.outlineVariant,
                  width: 1.5,
                ),
                padding: const EdgeInsets.symmetric(vertical: 14),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(AppRadius.button),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build countdown timer
  Widget _buildTimer(BuildContext context, String timerDisplay, int remainingSeconds) {
    final colorScheme = Theme.of(context).colorScheme;

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          FaIcon(FontAwesomeIcons.clock, size: 16, color: colorScheme.onSurfaceVariant),
          const SizedBox(width: 8),
          Text(
            'Thời gian thanh toán: ',
            style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
          ),
          Text(
            timerDisplay,
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.bold,
              color: remainingSeconds < 300
                  ? AppColors.danger
                  : colorScheme.onSurface,
            ),
          ),
        ],
      ),
    );
  }

  /// Copy text to clipboard
  void _copyToClipboard(BuildContext context, String text) {
    Clipboard.setData(ClipboardData(text: text));
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('Đã sao chép: $text'),
        duration: const Duration(seconds: 1),
        behavior: SnackBarBehavior.floating,
      ),
    );
  }

  /// Show payment info dialog
  void _showInfoDialog(BuildContext context) {
    showDialog<void>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Hướng dẫn thanh toán'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              'Đây là nội dung hướng dẫn sử dụng cho tính năng Thanh toán:',
              style: TextStyle(fontSize: 14),
            ),
            const SizedBox(height: 12),
            _buildInfoItem('Quét mã QR bằng app ngân hàng hoặc ví điện tử'),
            _buildInfoItem('Chuyển khoản theo thông tin được cung cấp'),
            _buildInfoItem('Ghi đúng nội dung chuyển khoản'),
            _buildInfoItem('Upload hóa đơn sau khi chuyển khoản'),
            _buildInfoItem('Thanh toán tối thiểu 20% giá trị đơn hàng'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Đóng'),
          ),
        ],
      ),
    );
  }

  /// Build info item for dialog
  Widget _buildInfoItem(String text) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text('• ', style: TextStyle(fontSize: 14)),
          Expanded(child: Text(text, style: const TextStyle(fontSize: 14))),
        ],
      ),
    );
  }

  /// Select image for bill
  Future<void> _selectImage(
    BuildContext context,
    ValueNotifier<String?> selectedImagePath,
  ) async {
    final colorScheme = Theme.of(context).colorScheme;

    // Show bottom sheet to select camera or gallery
    final ImageSource? source = await showModalBottomSheet<ImageSource>(
      context: context,
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.circular(AppRadius.card)),
      ),
      builder: (context) => Container(
        padding: const EdgeInsets.all(AppSpacing.md),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              'Chọn ảnh hóa đơn',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
                color: colorScheme.onSurface,
              ),
            ),
            const SizedBox(height: AppSpacing.md),
            ListTile(
              leading: FaIcon(
                FontAwesomeIcons.camera,
                color: colorScheme.primary,
              ),
              title: const Text('Chụp ảnh'),
              onTap: () => Navigator.of(context).pop(ImageSource.camera),
            ),
            ListTile(
              leading: FaIcon(
                FontAwesomeIcons.image,
                color: colorScheme.primary,
              ),
              title: const Text('Chọn từ thư viện'),
              onTap: () => Navigator.of(context).pop(ImageSource.gallery),
            ),
            const SizedBox(height: AppSpacing.sm),
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('Hủy'),
            ),
          ],
        ),
      ),
    );

    if (source == null || !context.mounted) return;

    try {
      // Pick image
      final picker = ImagePicker();
      final pickedFile = await picker.pickImage(
        source: source,
        maxWidth: 1920,
        maxHeight: 1080,
        imageQuality: 85,
      );

      if (pickedFile == null || !context.mounted) return;

      selectedImagePath.value = pickedFile.path;

      // Show success feedback
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Row(
            children: [
              FaIcon(FontAwesomeIcons.circleCheck, color: Colors.white, size: 20),
              SizedBox(width: 12),
              Text('Đã chọn ảnh. Nhấn "Upload bill chuyển khoản" để gửi.'),
            ],
          ),
          backgroundColor: AppColors.success,
          duration: Duration(seconds: 2),
        ),
      );
    } catch (e) {
      if (!context.mounted) return;

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('Lỗi khi chọn ảnh: ${e.toString()}'),
          backgroundColor: AppColors.danger,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  /// Upload bill to server
  Future<void> _uploadBill(
    BuildContext context,
    WidgetRef ref,
    ValueNotifier<String?> selectedImagePath,
    ValueNotifier<bool> isUploadingBill,
  ) async {
    final colorScheme = Theme.of(context).colorScheme;

    if (selectedImagePath.value == null) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('Vui lòng chọn ảnh hóa đơn trước'),
          backgroundColor: AppColors.danger,
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }

    // Show confirmation dialog
    final bool? confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Xác nhận upload'),
        content: const Text(
          'Bạn có muốn upload hóa đơn này không?',
          style: TextStyle(fontSize: 14),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Hủy'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: ElevatedButton.styleFrom(
              backgroundColor: colorScheme.primary,
            ),
            child: const Text('Upload'),
          ),
        ],
      ),
    );

    if (confirmed != true || !context.mounted) return;

    try {
      // Start upload
      isUploadingBill.value = true;

      final repository = await ref.read(orderRepositoryProvider.future);
      final result = await repository.uploadBill(
        filePath: selectedImagePath.value!,
        orderId: orderId,
      );

      if (!context.mounted) return;

      isUploadingBill.value = false;

      // Show success message and navigate
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Row(
            children: [
              FaIcon(FontAwesomeIcons.circleCheck, color: Colors.white, size: 20),
              SizedBox(width: 12),
              Text('Upload hóa đơn thành công!'),
            ],
          ),
          backgroundColor: AppColors.success,
          duration: Duration(seconds: 2),
        ),
      );

      // Navigate to order success page after successful upload
      Future.delayed(const Duration(milliseconds: 500), () {
        if (context.mounted) {
          context.pushReplacementNamed(
            RouteNames.orderSuccess,
            queryParameters: {
              'orderNumber': orderId,
              'isNegotiation': 'false',
            },
          );
        }
      });
    } catch (e) {
      if (!context.mounted) return;

      isUploadingBill.value = false;

      // Show error message
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Row(
            children: [
              const FaIcon(FontAwesomeIcons.circleXmark, color: Colors.white, size: 20),
              const SizedBox(width: 12),
              Expanded(
                child: Text('Lỗi upload: ${e.toString()}'),
              ),
            ],
          ),
          backgroundColor: AppColors.danger,
          duration: const Duration(seconds: 3),
        ),
      );
    }
  }
}
