/// Page: Order Detail Page
///
/// Displays detailed order information including status timeline, delivery info, and products.
library;

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/enums/status_color.dart';
import 'package:worker/core/router/app_router.dart';
import 'package:worker/core/theme/colors.dart';
import 'package:worker/core/utils/extensions.dart';
import 'package:worker/core/widgets/loading_indicator.dart';
import 'package:worker/features/account/domain/entities/address.dart';
import 'package:worker/features/orders/domain/entities/order_detail.dart';
import 'package:worker/features/orders/presentation/providers/orders_provider.dart';

/// Order Detail Page
///
/// Features:
/// - Status timeline with progress tracking
/// - Delivery information
/// - Customer details
/// - Product list
/// - Order summary
/// - Action buttons (Contact customer, Update status)
class OrderDetailPage extends ConsumerWidget {
  const OrderDetailPage({required this.orderId, super.key});
  final String orderId;

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

    return PopScope(
      onPopInvoked: (didPop) {
        if (didPop) {
          // Dispose providers when leaving the page
          ref..invalidate(updateOrderAddressProvider)
          ..invalidate(cancelOrderProvider);
        }
      },
      child: Scaffold(
        backgroundColor: colorScheme.surfaceContainerLowest,
        appBar: AppBar(
          leading: IconButton(
            icon: FaIcon(FontAwesomeIcons.arrowLeft, color: colorScheme.onSurface, size: 20),
            onPressed: () => context.pop(),
          ),
        title: Text(
          'Chi tiết đơn hàng',
          style: TextStyle(color: colorScheme.onSurface),
        ),
        actions: [
          IconButton(
            icon: FaIcon(FontAwesomeIcons.shareNodes, color: colorScheme.onSurface, size: 20),
            onPressed: () {
              // TODO: Implement share functionality
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('Chức năng chia sẻ đang phát triển'),
                ),
              );
            },
          ),
          IconButton(
            icon: FaIcon(FontAwesomeIcons.print, color: colorScheme.onSurface, size: 20),
            onPressed: () {
              // TODO: Implement print functionality
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Chức năng in đang phát triển')),
              );
            },
          ),
        ],
        elevation: AppBarSpecs.elevation,
        backgroundColor: colorScheme.surface,
        foregroundColor: colorScheme.onSurface,
        centerTitle: false,
      ),
      body: orderDetailAsync.when(
        data: (orderDetail) {
          return Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.only(bottom: 100),
                child: Column(
                  children: [
                    // Status Timeline Card
                    _buildStatusTimelineCard(context, orderDetail),

                    // Delivery/Address Information Card
                    _buildAddressInfoCard(context, ref, orderDetail),

                    // Invoice Information Card
                    _buildInvoiceInfoCard(context, ref, orderDetail),

                    // Invoices List Card
                    _buildInvoicesListCard(context, orderDetail),

                    // Products List Card
                    _buildProductsListCard(context, orderDetail),

                    // Order Summary Card
                    _buildOrderSummaryCard(context, orderDetail),

                    // Payment History Card
                    if (orderDetail.order.totalRemaining > 0) ...[
                      _buildPaymentHistoryCard(context, orderDetail),
                    ],

                    // Cancel Order Button
                    // Use API flag to determine if cancellation is allowed
                    if (orderDetail.order.isAllowCancel) ...[
                      const SizedBox(height: 16),
                      _buildCancelOrderButton(context, ref, orderDetail),
                    ],

                    const SizedBox(height: 16),
                  ],
                ),
              ),

              // Fixed Action Buttons
              Positioned(
                bottom: 0,
                left: 0,
                right: 0,
                child: _buildActionButtons(context, orderDetail),
              ),
            ],
          );
        },
        loading: () => const CustomLoadingIndicator(),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const FaIcon(
                FontAwesomeIcons.circleExclamation,
                size: 64,
                color: AppColors.danger,
              ),
              const SizedBox(height: 16),
              Text(
                'Không thể tải thông tin đơn hàng',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: colorScheme.onSurface,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                error.toString(),
                style: TextStyle(
                  fontSize: 14,
                  color: colorScheme.onSurfaceVariant,
                ),
                textAlign: TextAlign.center,
              ),
              const SizedBox(height: 24),
              ElevatedButton.icon(
                onPressed: () {
                  ref.invalidate(orderDetailProvider(orderId));
                },
                icon: const FaIcon(FontAwesomeIcons.arrowsRotate, size: 16),
                label: const Text('Thử lại'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: colorScheme.primary,
                  foregroundColor: colorScheme.onPrimary,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      ),
    );
  }

  /// Build Status Timeline Card
  Widget _buildStatusTimelineCard(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    final order = orderDetail.order;
    final timeline = orderDetail.timeline;

    return Card(
      margin: const EdgeInsets.all(16),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Order Number and Status Badge
            Text(
              '#${order.name}',
              style: TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: colorScheme.primary,
              ),
            ),

            const SizedBox(height: 12,),
            _buildStatusBadge(order.status, order.statusColor),

            const SizedBox(height: 24),

            // Status Timeline
            ...timeline.asMap().entries.map((entry) {
              final index = entry.key;
              final item = entry.value;
              final isLast = index == timeline.length - 1;

              return _buildTimelineItem(
                context,
                title: item.label,
                date: item.value,
                status: item.status,
                isLast: isLast,
              );
            }),
          ],
        ),
      ),
    );
  }

  /// Build Timeline Item
  Widget _buildTimelineItem(
    BuildContext context, {
    required String title,
    String? date,
    required String status, // 'Success', 'Warning', 'Secondary', etc.
    required bool isLast,
  }) {
    final colorScheme = Theme.of(context).colorScheme;
    final statusColor = StatusColor.fromString(status) ?? StatusColor.secondary;

    Color iconColor;
    Color iconBgColor;
    IconData iconData;

    if (statusColor == StatusColor.success) {
      iconColor = colorScheme.onPrimary;
      iconBgColor = statusColor.color;
      iconData = FontAwesomeIcons.check;
    } else if (statusColor == StatusColor.warning) {
      iconColor = colorScheme.onPrimary;
      iconBgColor = statusColor.color;
      iconData = FontAwesomeIcons.gear;
    } else {
      // Secondary or other
      iconColor = colorScheme.onSurfaceVariant;
      iconBgColor = colorScheme.surfaceContainerHighest;
      iconData = _getIconForTitle(title);
    }

    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // Timeline icon and line
        Column(
          children: [
            Container(
              width: 24,
              height: 24,
              decoration: BoxDecoration(
                color: iconBgColor,
                shape: BoxShape.circle,
              ),
              child: Center(child: FaIcon(iconData, size: 10, color: iconColor)),
            ),
            if (!isLast)
              Container(
                width: 2,
                height: 40,
                color: colorScheme.outlineVariant,
                margin: const EdgeInsets.symmetric(vertical: 4),
              ),
          ],
        ),

        const SizedBox(width: 16),

        // Timeline content
        Expanded(
          child: Padding(
            padding: EdgeInsets.only(bottom: isLast ? 0 : 20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  title,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  date ?? 'Đang cập nhật',
                  style: TextStyle(
                    fontSize: 12,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// Get icon for timeline title
  IconData _getIconForTitle(String title) {
    if (title.contains('Vận chuyển')) {
      return FontAwesomeIcons.truck;
    } else if (title.contains('Giao hàng')) {
      return FontAwesomeIcons.box;
    }
    return FontAwesomeIcons.solidCircle;
  }

  /// Build Status Badge
  Widget _buildStatusBadge(String status, String statusColorName) {
    final statusColor = StatusColor.fromString(statusColorName) ?? StatusColor.secondary;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
      decoration: BoxDecoration(
        color: statusColor.light,
        borderRadius: BorderRadius.circular(20),
        border: Border.all(
          color: statusColor.border,
          width: 1,
        ),
      ),
      child: Text(
        status,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w600,
          color: statusColor.color,
        ),
      ),
    );
  }

  /// Build Address Info Card
  Widget _buildAddressInfoCard(
    BuildContext context,
    WidgetRef ref,
    OrderDetail orderDetail,
  ) {
    final colorScheme = Theme.of(context).colorScheme;
    final order = orderDetail.order;
    final shippingAddress = orderDetail.shippingAddress;
    final dateFormatter = DateFormat('dd/MM/yyyy');

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.truck,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Text(
                  'Thông tin giao hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Address Section with Label + Button
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  'Địa chỉ nhận hàng',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w700,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
                Builder(
                  builder: (context) {
                    // Use API flag to determine if editing is allowed
                    if (orderDetail.shippingAddress.isAllowEdit) {
                      return TextButton(
                        onPressed: () async {
                          // Navigate to address selection and wait for result
                          final result = await context.push<Address>(
                            '/account/addresses',
                            extra: {
                              'selectMode': true,
                              'currentAddress': shippingAddress,
                            },
                          );

                          // If user selected an address, update the order
                          if (result != null && context.mounted) {
                            // Show loading indicator
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('Đang cập nhật địa chỉ...'),
                                duration: Duration(seconds: 1),
                              ),
                            );

                            // Update shipping address (keep billing address the same)
                            await ref
                                .read(updateOrderAddressProvider.notifier)
                                .updateAddress(
                              orderId: orderId,
                              shippingAddressName: result.name,
                              customerAddress: orderDetail.billingAddress.name,
                            );

                            // Check if update was successful
                            final updateState =
                            ref.read(updateOrderAddressProvider)
                              ..when(
                                data: (_) {
                                  // Refresh order detail to show updated address
                                  ref.invalidate(orderDetailProvider(orderId));

                                  // Show success message
                                  if (context.mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text(
                                          'Cập nhật địa chỉ giao hàng thành công',
                                        ),
                                        backgroundColor: AppColors.success,
                                      ),
                                    );
                                  }
                                },
                                error: (error, _) {
                                  // Show error message
                                  if (context.mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: Text(
                                          'Lỗi: ${error.toString()}',
                                        ),
                                        backgroundColor: AppColors.danger,
                                      ),
                                    );
                                  }
                                },
                                loading: () {},
                              );
                          }
                        },
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          side: BorderSide(color: colorScheme.outlineVariant),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: Text(
                          'Cập nhật',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w700,
                            color: colorScheme.primary,
                          ),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  },
                ),
              ],
            ),

            const SizedBox(height: 8),

            // Address Box
            Container(
              padding: const EdgeInsets.all(12),
              width: double.infinity,
              decoration: BoxDecoration(
                border: Border.all(color: colorScheme.outlineVariant),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    shippingAddress.addressTitle,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    shippingAddress.phone,
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${shippingAddress.addressLine1}\n${shippingAddress.wardName}, ${shippingAddress.cityName}',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 16),

            // Pickup Date
            Text(
              'Ngày lấy hàng',
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurfaceVariant,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              dateFormatter.format(DateTime.parse(order.deliveryDate)),
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w500,
                color: colorScheme.onSurface,
              ),
            ),

            if (order.description.isNotEmpty) ...[ const SizedBox(height: 16),

              // Notes
              Text(
                'Ghi chú',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: colorScheme.onSurfaceVariant,
                ),
              ),
              const SizedBox(height: 4),
              Text(
                order.description,
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                  color: colorScheme.onSurface,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }

  /// Build Invoice Info Card
  Widget _buildInvoiceInfoCard(
    BuildContext context,
    WidgetRef ref,
    OrderDetail orderDetail,
  ) {
    final colorScheme = Theme.of(context).colorScheme;
    final billingAddress = orderDetail.billingAddress;

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // Title + Update Button
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    FaIcon(
                      FontAwesomeIcons.fileInvoice,
                      color: colorScheme.primary,
                      size: 18,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      'Thông tin hóa đơn',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: colorScheme.onSurface,
                      ),
                    ),
                  ],
                ),
                Builder(
                  builder: (context) {
                    // Use API flag to determine if editing is allowed
                    if (orderDetail.billingAddress.isAllowEdit) {
                      return TextButton(
                        onPressed: () async {
                          // Navigate to address selection and wait for result
                          final result = await context.push<Address>(
                            '/account/addresses',
                            extra: {
                              'selectMode': true,
                              'currentAddress': billingAddress,
                            },
                          );

                          // If user selected an address, update the order
                          if (result != null && context.mounted) {
                            // Show loading indicator
                            ScaffoldMessenger.of(context).showSnackBar(
                              const SnackBar(
                                content: Text('Đang cập nhật địa chỉ...'),
                                duration: Duration(seconds: 1),
                              ),
                            );

                            // Update billing address (keep shipping address the same)
                            await ref
                                .read(updateOrderAddressProvider.notifier)
                                .updateAddress(
                              orderId: orderId,
                              shippingAddressName: orderDetail.shippingAddress.name,
                              customerAddress: result.name,
                            );

                            // Check if update was successful
                            final updateState =
                            ref.read(updateOrderAddressProvider)
                              ..when(
                                data: (_) {
                                  // Refresh order detail to show updated address
                                  ref.invalidate(orderDetailProvider(orderId));

                                  // Show success message
                                  if (context.mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      const SnackBar(
                                        content: Text(
                                          'Cập nhật địa chỉ hóa đơn thành công',
                                        ),
                                        backgroundColor: AppColors.success,
                                      ),
                                    );
                                  }
                                },
                                error: (error, _) {
                                  // Show error message
                                  if (context.mounted) {
                                    ScaffoldMessenger.of(context).showSnackBar(
                                      SnackBar(
                                        content: Text(
                                          'Lỗi: ${error.toString()}',
                                        ),
                                        backgroundColor: AppColors.danger,
                                      ),
                                    );
                                  }
                                },
                                loading: () {},
                              );
                          }
                        },
                        style: TextButton.styleFrom(
                          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                          side: BorderSide(color: colorScheme.outlineVariant),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: Text(
                          'Cập nhật',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w700,
                            color: colorScheme.primary,
                          ),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  },
                ),

              ],
            ),

            const SizedBox(height: 12),

            // Invoice Address Box
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                border: Border.all(color: colorScheme.outlineVariant),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    billingAddress.addressTitle,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  if (billingAddress.taxCode != null &&
                      billingAddress.taxCode!.isNotEmpty) ...[
                    const SizedBox(height: 2),
                    Text(
                      'Mã số thuế: ${billingAddress.taxCode}',
                      style: TextStyle(
                        fontSize: 14,
                        color: colorScheme.onSurfaceVariant,
                      ),
                    ),
                  ],
                  const SizedBox(height: 2),
                  Text(
                    'Số điện thoại: ${billingAddress.phone}',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    'Email: ${billingAddress.email}',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    'Địa chỉ: ${billingAddress.addressLine1}, ${billingAddress.wardName}, ${billingAddress.cityName}',
                    style: TextStyle(
                      fontSize: 14,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build Invoices List Card
  Widget _buildInvoicesListCard(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    final invoices = orderDetail.invoices;

    if (invoices.isEmpty) {
      return const SizedBox.shrink();
    }

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.fileInvoiceDollar,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Text(
                  'Hóa đơn đã xuất',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Invoice Items (Mock data for now)
            ...invoices.map((e) => _buildInvoiceItem(
              context,
              invoiceId: e.name,
              date: e.postingDate,
              amount: e.grandTotal.toVNCurrency,
              onTap: () {
                // TODO: Navigate to invoice detail
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Chức năng đang phát triển')),
                );
              },
            ),),
          ],
        ),
      ),
    );
  }

  /// Build Invoice Item
  Widget _buildInvoiceItem(
    BuildContext context, {
    required String invoiceId,
    required String date,
    required String amount,
    required VoidCallback onTap,
  }) {
    final colorScheme = Theme.of(context).colorScheme;
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(color: colorScheme.outlineVariant),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  colors: [colorScheme.primary, colorScheme.primaryContainer],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Center(
                child: FaIcon(
                  FontAwesomeIcons.fileInvoice,
                  color: colorScheme.onPrimary,
                  size: 18,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    invoiceId,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    'Ngày xuất: $date',
                    style: TextStyle(
                      fontSize: 12,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 4,),
            Text(
              amount,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w700,
                color: AppColors.danger,
              ),
            ),
            const SizedBox(width: 8),
            FaIcon(
              FontAwesomeIcons.chevronRight,
              size: 14,
              color: colorScheme.onSurfaceVariant,
            ),
          ],
        ),
      ),
    );
  }

  /// Build Products List Card
  Widget _buildProductsListCard(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    final items = orderDetail.items;

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.box,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Text(
                  'Sản phẩm đặt hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            ...items.map(
              (item) => Container(
                margin: const EdgeInsets.only(bottom: 12),
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  border: Border.all(color: colorScheme.outlineVariant),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // Product Image
                    if (item.thumbnail != null)
                      ClipRRect(
                        borderRadius: BorderRadius.circular(6),
                        child: CachedNetworkImage(
                          imageUrl: item.thumbnail!,
                          width: 60,
                          height: 60,
                          fit: BoxFit.cover,
                          placeholder: (context, url) => Container(
                            width: 60,
                            height: 60,
                            color: colorScheme.surfaceContainerHighest,
                            child: const Center(
                              child: CustomLoadingIndicator(size: 20),
                            ),
                          ),
                          errorWidget: (context, url, error) => Container(
                            width: 60,
                            height: 60,
                            color: colorScheme.surfaceContainerHighest,
                            child: FaIcon(
                              FontAwesomeIcons.image,
                              color: colorScheme.onSurfaceVariant,
                              size: 28,
                            ),
                          ),
                        ),
                      )
                    else
                      Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          color: colorScheme.surfaceContainerHighest,
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: FaIcon(
                          FontAwesomeIcons.image,
                          color: colorScheme.onSurfaceVariant,
                          size: 28,
                        ),
                      ),

                    const SizedBox(width: 12),

                    // Product Info
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            item.itemName,
                            style: TextStyle(
                              fontSize: 14,
                              fontWeight: FontWeight.w600,
                              color: colorScheme.onSurface,
                            ),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            'Mã: ${item.itemCode}',
                            style: TextStyle(
                              fontSize: 12,
                              color: colorScheme.onSurfaceVariant,
                            ),
                          ),
                          const SizedBox(height: 8),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    'Số lượng:',
                                    style: TextStyle(
                                      fontSize: 11,
                                      color: colorScheme.onSurfaceVariant,
                                    ),
                                  ),
                                  Text(
                                    '${item.qtyOfSm} m²',
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: colorScheme.onSurface,
                                    ),
                                  ),
                                ],
                              ),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                children: [
                                  Text(
                                    '${item.price.toVNCurrency}/m²',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: colorScheme.onSurfaceVariant,
                                    ),
                                  ),
                                  Text(
                                    item.totalAmount.toVNCurrency,
                                    style: const TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.w600,
                                      color: AppColors.danger,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build Order Summary Card
  Widget _buildOrderSummaryCard(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    final order = orderDetail.order;
    final paymentTerms = orderDetail.paymentTerms;

    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.receipt,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Text(
                  'Tổng kết đơn hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            _buildSummaryRow(context, 'Tổng tiền hàng:', order.total.toVNCurrency),
            const SizedBox(height: 8),

            if (order.totalRemaining > 0) ...[
              _buildSummaryRow(
                context,
                'Còn lại:',
                order.totalRemaining.toVNCurrency,
                valueColor: AppColors.warning,
              ),
              const SizedBox(height: 8),
            ],

            const Divider(height: 24),

            _buildSummaryRow(
              context,
              'Tổng cộng:',
              order.grandTotal.toVNCurrency,
              isTotal: true,
            ),

            const Divider(height: 24),

            // Payment Terms
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.creditCard,
                  size: 14,
                  color: colorScheme.onSurfaceVariant,
                ),
                const SizedBox(width: 6),
                Text(
                  'Điều khoản thanh toán:',
                  style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
                ),
              ],
            ),
            const SizedBox(height: 4),
            Text(
              paymentTerms.name,
              style: TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w600,
                color: colorScheme.onSurface,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              paymentTerms.description,
              style: TextStyle(
                fontSize: 12,
                color: colorScheme.onSurfaceVariant,
                height: 1.4,
              ),
            ),

          ],
        ),
      ),
    );
  }

  /// Build Payment History Card
  Widget _buildPaymentHistoryCard(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    final order = orderDetail.order;
    final payments = orderDetail.payments;


    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      elevation: 1,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
      child: Padding(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          spacing: 16,
          children: [
            Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.clockRotateLeft,
                  color: colorScheme.primary,
                  size: 18,
                ),
                const SizedBox(width: 8),
                Text(
                  'Lịch sử thanh toán',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: colorScheme.onSurface,
                  ),
                ),
              ],
            ),


            ...payments.map((e) => _buildPaymentItem(
              context,
              paymentId: e.name,
              date: e.creationDate,
              amount: e.amount.toVNCurrency,
              onTap: () {
                // TODO: Show payment detail modal
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('Chi tiết thanh toán')),
                );
              },
            )),


            // Payment Summary
            Container(
              padding: const EdgeInsets.only(top: 12),
              decoration: BoxDecoration(
                border: Border(
                  top: BorderSide(color: colorScheme.outlineVariant, width: 1),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    'Còn lại:',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                  Text(
                    order.totalRemaining.toVNCurrency,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: AppColors.danger,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build Payment Item
  Widget _buildPaymentItem(
    BuildContext context, {
    required String paymentId,
    required String date,
    required String amount,
    required VoidCallback onTap,
  }) {
    final colorScheme = Theme.of(context).colorScheme;
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(color: colorScheme.outlineVariant),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: const BoxDecoration(
                color: Color(0xFFD1FAE5),
                shape: BoxShape.circle,
              ),
              child: const Center(
                child: FaIcon(
                  FontAwesomeIcons.check,
                  color: Color(0xFF065F46),
                  size: 16,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    paymentId,
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: colorScheme.onSurface,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    date,
                    style: TextStyle(
                      fontSize: 12,
                      color: colorScheme.onSurfaceVariant,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 4),
            Text(
              amount,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF065F46),
              ),
            ),
            const SizedBox(width: 8),
            FaIcon(
              FontAwesomeIcons.chevronRight,
              size: 14,
              color: colorScheme.onSurfaceVariant,
            ),
          ],
        ),
      ),
    );
  }

  /// Build Summary Row
  Widget _buildSummaryRow(
    BuildContext context,
    String label,
    String value, {
    bool isTotal = false,
    Color? valueColor,
  }) {
    final colorScheme = Theme.of(context).colorScheme;
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: isTotal ? 14 : 14,
            fontWeight: isTotal ? FontWeight.w600 : FontWeight.normal,
            color: isTotal ? colorScheme.onSurface : colorScheme.onSurfaceVariant,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: isTotal ? 16 : 14,
            fontWeight: isTotal ? FontWeight.w700 : FontWeight.w500,
            color:
                valueColor ?? (isTotal ? AppColors.danger : colorScheme.onSurface),
          ),
        ),
      ],
    );
  }

  /// Build Action Buttons
  Widget _buildActionButtons(BuildContext context, OrderDetail orderDetail) {
    final colorScheme = Theme.of(context).colorScheme;
    return Container(
      decoration: BoxDecoration(
        color: colorScheme.surface,
        boxShadow: [
          BoxShadow(
            color: colorScheme.shadow.withValues(alpha: 0.1),
            blurRadius: 15,
            offset: const Offset(0, -4),
          ),
        ],
      ),
      padding: const EdgeInsets.all(16),
      child: Row(
        spacing: 12,
        children: [
          Expanded(
            child: ElevatedButton.icon(
              onPressed: () {
                // Navigate to payment QR page
                context.push(
                  '${RouteNames.paymentQr}?orderId=${orderDetail.order.name}',
                );
              },
              icon: const FaIcon(FontAwesomeIcons.creditCard, size: 18),
              label: const Text('Thanh toán'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                backgroundColor: colorScheme.primary,
                foregroundColor: colorScheme.onPrimary,
                elevation: 0,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
          Expanded(
            child: OutlinedButton.icon(
              onPressed: () {
                // TODO: Navigate to chat/support
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Liên hệ hỗ trợ...'),
                  ),
                );
              },
              icon: const FaIcon(FontAwesomeIcons.comments, size: 18),
              label: const Text('Liên hệ hỗ trợ'),
              style: OutlinedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                side: BorderSide(
                  color: colorScheme.outlineVariant,
                  width: 2,
                ),
                foregroundColor: colorScheme.onSurface,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// Build Cancel Order Button
  Widget _buildCancelOrderButton(
    BuildContext context,
    WidgetRef ref,
    OrderDetail orderDetail,
  ) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      child: OutlinedButton.icon(
        onPressed: () async {
          // Show confirmation dialog
          final confirmed = await showDialog<bool>(
            context: context,
            builder: (context) => AlertDialog(
              title: const Text('Xác nhận hủy đơn'),
              content: Text(
                'Bạn có chắc chắn muốn hủy đơn hàng ${orderDetail.order.name}?\n\nHành động này không thể hoàn tác.',
              ),
              actions: [
                TextButton(
                  onPressed: () => Navigator.of(context).pop(false),
                  child: const Text('Không'),
                ),
                ElevatedButton(
                  onPressed: () => Navigator.of(context).pop(true),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: AppColors.danger,
                    foregroundColor: Theme.of(context).colorScheme.onPrimary,
                  ),
                  child: const Text('Hủy đơn'),
                ),
              ],
            ),
          );

          // If user confirmed, proceed with cancellation
          if (confirmed == true && context.mounted) {
            // Show loading indicator
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Row(
                  children: [
                    CustomLoadingIndicator(
                      size: 20,
                      color: Theme.of(context).colorScheme.onPrimary,
                    ),
                    const SizedBox(width: 12),
                    const Text('Đang hủy đơn hàng...'),
                  ],
                ),
                duration: const Duration(seconds: 2),
              ),
            );

            // Call cancel order API
            await ref.read(cancelOrderProvider.notifier).cancel(orderId);

            // Check result
            final cancelState = ref.read(cancelOrderProvider);
            if (context.mounted) {
              cancelState.when(
                data: (_) {
                  // Success: Invalidate order providers and show success message
                  ref.invalidate(ordersProvider);
                  ref.invalidate(orderDetailProvider(orderId));

                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('Đã hủy đơn hàng thành công'),
                      backgroundColor: AppColors.success,
                    ),
                  );

                  // Pop back to orders list
                  context.pop();
                },
                error: (error, _) {
                  // Error: Show error message
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('Lỗi: ${error.toString()}'),
                      backgroundColor: AppColors.danger,
                    ),
                  );
                },
                loading: () {},
              );
            }
          }
        },
        icon: const FaIcon(FontAwesomeIcons.xmark, size: 18),
        label: const Text('Hủy đơn hàng'),
        style: OutlinedButton.styleFrom(
          padding: const EdgeInsets.symmetric(vertical: 14),
          side: const BorderSide(
            color: AppColors.danger,
            width: 2,
          ),
          foregroundColor: AppColors.danger,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          minimumSize: const Size(double.infinity, 48),
        ),
      ),
    );
  }
}
