/// 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/theme/colors.dart';
import 'package:worker/core/utils/extensions.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 orderDetailAsync = ref.watch(orderDetailProvider(orderId));

    return PopScope(
      onPopInvoked: (didPop) {
        if (didPop) {
          // Dispose providers when leaving the page
          ref.invalidate(updateOrderAddressProvider);
          ref.invalidate(cancelOrderProvider);
        }
      },
      child: Scaffold(
        backgroundColor: const Color(0xFFF4F6F8),
        appBar: AppBar(
          leading: IconButton(
            icon: const FaIcon(FontAwesomeIcons.arrowLeft, color: Colors.black, size: 20),
            onPressed: () => context.pop(),
          ),
        title: const Text(
          'Chi tiết đơn hàng',
          style: TextStyle(color: Colors.black),
        ),
        actions: [
          IconButton(
            icon: const FaIcon(FontAwesomeIcons.shareNodes, color: Colors.black, 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: const FaIcon(FontAwesomeIcons.print, color: Colors.black, 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: AppColors.white,
        foregroundColor: AppColors.grey900,
        centerTitle: false,
      ),
      body: orderDetailAsync.when(
        data: (orderDetail) {
          return Stack(
            children: [
              SingleChildScrollView(
                padding: const EdgeInsets.only(bottom: 100),
                child: Column(
                  children: [
                    // Status Timeline Card
                    _buildStatusTimelineCard(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(orderDetail),

                    // Order Summary Card
                    _buildOrderSummaryCard(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 Center(child: CircularProgressIndicator()),
        error: (error, stack) => Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const FaIcon(
                FontAwesomeIcons.circleExclamation,
                size: 64,
                color: AppColors.danger,
              ),
              const SizedBox(height: 16),
              const Text(
                'Không thể tải thông tin đơn hàng',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                  color: AppColors.grey900,
                ),
              ),
              const SizedBox(height: 8),
              Text(
                error.toString(),
                style: const TextStyle(
                  fontSize: 14,
                  color: AppColors.grey500,
                ),
                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: AppColors.primaryBlue,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(
                    horizontal: 24,
                    vertical: 12,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      ),
    );
  }

  /// Build Status Timeline Card
  Widget _buildStatusTimelineCard(OrderDetail orderDetail) {
    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: const TextStyle(
                fontSize: 20,
                fontWeight: FontWeight.w700,
                color: AppColors.primaryBlue,
              ),
            ),

            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(
                title: item.label,
                date: item.value,
                status: item.status,
                isLast: isLast,
              );
            }),
          ],
        ),
      ),
    );
  }

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

    Color iconColor;
    Color iconBgColor;
    IconData iconData;

    if (statusColor == StatusColor.success) {
      iconColor = Colors.white;
      iconBgColor = statusColor.color;
      iconData = FontAwesomeIcons.check;
    } else if (statusColor == StatusColor.warning) {
      iconColor = Colors.white;
      iconBgColor = statusColor.color;
      iconData = FontAwesomeIcons.gear;
    } else {
      // Secondary or other
      iconColor = AppColors.grey500;
      iconBgColor = AppColors.grey100;
      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: AppColors.grey100,
                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: const TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
                const SizedBox(height: 2),
                Text(
                  date ?? 'Đang cập nhật',
                  style: const TextStyle(
                    fontSize: 12,
                    color: AppColors.grey500,
                  ),
                ),
              ],
            ),
          ),
        ),
      ],
    );
  }

  /// 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 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: [
            const Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.truck,
                  color: AppColors.primaryBlue,
                  size: 18,
                ),
                SizedBox(width: 8),
                Text(
                  'Thông tin giao hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Address Section with Label + Button
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text(
                  'Địa chỉ nhận hàng',
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w700,
                    color: AppColors.grey500,
                  ),
                ),
                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: const BorderSide(color: AppColors.grey100),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          'Cập nhật',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w700,
                            color: AppColors.primaryBlue,
                          ),
                        ),
                      );
                    }
                    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: AppColors.grey100),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    shippingAddress.addressTitle,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: AppColors.grey900,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    shippingAddress.phone,
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.grey500,
                    ),
                  ),
                  const SizedBox(height: 4),
                  Text(
                    '${shippingAddress.addressLine1}\n${shippingAddress.wardName}, ${shippingAddress.cityName}',
                    style: const TextStyle(
                      fontSize: 14,
                      color: AppColors.grey500,
                    ),
                  ),
                ],
              ),
            ),

            const SizedBox(height: 16),

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

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

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

  /// Build Invoice Info Card
  Widget _buildInvoiceInfoCard(
    BuildContext context,
    WidgetRef ref,
    OrderDetail orderDetail,
  ) {
    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: [
                const Row(
                  children: [
                    FaIcon(
                      FontAwesomeIcons.fileInvoice,
                      color: AppColors.primaryBlue,
                      size: 18,
                    ),
                    SizedBox(width: 8),
                    Text(
                      'Thông tin hóa đơn',
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w600,
                        color: AppColors.grey900,
                      ),
                    ),
                  ],
                ),
                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: const BorderSide(color: AppColors.grey100),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(8),
                          ),
                        ),
                        child: const Text(
                          'Cập nhật',
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.w700,
                            color: AppColors.primaryBlue,
                          ),
                        ),
                      );
                    }
                    return const SizedBox.shrink();
                  },
                ),

              ],
            ),

            const SizedBox(height: 12),

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

  /// Build Invoices List Card
  Widget _buildInvoicesListCard(BuildContext context, OrderDetail orderDetail) {
    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: [
            const Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.fileInvoiceDollar,
                  color: AppColors.primaryBlue,
                  size: 18,
                ),
                SizedBox(width: 8),
                Text(
                  'Hóa đơn đã xuất',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // Invoice Items (Mock data for now)
            ...invoices.map((e) => _buildInvoiceItem(
              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({
    required String invoiceId,
    required String date,
    required String amount,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(color: AppColors.grey100),
          borderRadius: BorderRadius.circular(8),
        ),
        child: Row(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                gradient: const LinearGradient(
                  colors: [AppColors.primaryBlue, Color(0xFF1d4ed8)],
                  begin: Alignment.topLeft,
                  end: Alignment.bottomRight,
                ),
                borderRadius: BorderRadius.circular(8),
              ),
              child: const Center(
                child: FaIcon(
                  FontAwesomeIcons.fileInvoice,
                  color: Colors.white,
                  size: 18,
                ),
              ),
            ),
            const SizedBox(width: 12),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    invoiceId,
                    style: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: AppColors.grey900,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    'Ngày xuất: $date',
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.grey500,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 4,),
            Text(
              amount,
              style: const TextStyle(
                fontSize: 14,
                fontWeight: FontWeight.w700,
                color: AppColors.danger,
              ),
            ),
            const SizedBox(width: 8),
            const FaIcon(
              FontAwesomeIcons.chevronRight,
              size: 14,
              color: AppColors.grey500,
            ),
          ],
        ),
      ),
    );
  }

  /// Build Products List Card
  Widget _buildProductsListCard(OrderDetail orderDetail) {
    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: [
            const Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.box,
                  color: AppColors.primaryBlue,
                  size: 18,
                ),
                SizedBox(width: 8),
                Text(
                  'Sản phẩm đặt hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
              ],
            ),

            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: AppColors.grey100),
                  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: AppColors.grey50,
                            child: const Center(
                              child: CircularProgressIndicator(strokeWidth: 2),
                            ),
                          ),
                          errorWidget: (context, url, error) => Container(
                            width: 60,
                            height: 60,
                            color: AppColors.grey50,
                            child: const FaIcon(
                              FontAwesomeIcons.image,
                              color: AppColors.grey500,
                              size: 28,
                            ),
                          ),
                        ),
                      )
                    else
                      Container(
                        width: 60,
                        height: 60,
                        decoration: BoxDecoration(
                          color: AppColors.grey50,
                          borderRadius: BorderRadius.circular(6),
                        ),
                        child: const FaIcon(
                          FontAwesomeIcons.image,
                          color: AppColors.grey500,
                          size: 28,
                        ),
                      ),

                    const SizedBox(width: 12),

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

  /// Build Order Summary Card
  Widget _buildOrderSummaryCard(OrderDetail orderDetail) {
    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: [
            const Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.receipt,
                  color: AppColors.primaryBlue,
                  size: 18,
                ),
                SizedBox(width: 8),
                Text(
                  'Tổng kết đơn hàng',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

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

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

            const Divider(height: 24),

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

            const Divider(height: 24),

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

          ],
        ),
      ),
    );
  }

  /// Build Payment History Card
  Widget _buildPaymentHistoryCard(BuildContext context, OrderDetail orderDetail) {
    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: [
            const Row(
              children: [
                FaIcon(
                  FontAwesomeIcons.clockRotateLeft,
                  color: AppColors.primaryBlue,
                  size: 18,
                ),
                SizedBox(width: 8),
                Text(
                  'Lịch sử thanh toán',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: AppColors.grey900,
                  ),
                ),
              ],
            ),


            ...payments.map((e) => _buildPaymentItem(
              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: const BoxDecoration(
                border: Border(
                  top: BorderSide(color: AppColors.grey100, width: 1),
                ),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text(
                    'Còn lại:',
                    style: TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w500,
                      color: AppColors.grey500,
                    ),
                  ),
                  Text(
                    order.totalRemaining.toVNCurrency,
                    style: const TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w700,
                      color: AppColors.danger,
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// Build Payment Item
  Widget _buildPaymentItem({
    required String paymentId,
    required String date,
    required String amount,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          border: Border.all(color: AppColors.grey100),
          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: const TextStyle(
                      fontSize: 14,
                      fontWeight: FontWeight.w600,
                      color: AppColors.grey900,
                    ),
                  ),
                  const SizedBox(height: 2),
                  Text(
                    date,
                    style: const TextStyle(
                      fontSize: 12,
                      color: AppColors.grey500,
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(width: 4),
            Text(
              amount,
              style: const TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.w600,
                color: Color(0xFF065F46),
              ),
            ),
            const SizedBox(width: 8),
            const FaIcon(
              FontAwesomeIcons.chevronRight,
              size: 14,
              color: AppColors.grey500,
            ),
          ],
        ),
      ),
    );
  }

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

  /// Build Action Buttons
  Widget _buildActionButtons(BuildContext context, OrderDetail orderDetail) {
    return Container(
      decoration: BoxDecoration(
        color: AppColors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.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: () {
                // TODO: Navigate to payment page
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(
                    content: Text('Chức năng thanh toán đang phát triển'),
                  ),
                );
              },
              icon: const FaIcon(FontAwesomeIcons.creditCard, size: 18),
              label: const Text('Thanh toán'),
              style: ElevatedButton.styleFrom(
                padding: const EdgeInsets.symmetric(vertical: 14),
                backgroundColor: AppColors.primaryBlue,
                foregroundColor: Colors.white,
                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: AppColors.grey100,
                  width: 2,
                ),
                foregroundColor: AppColors.grey900,
                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: Colors.white,
                  ),
                  child: const Text('Hủy đơn'),
                ),
              ],
            ),
          );

          // If user confirmed, proceed with cancellation
          if (confirmed == true && context.mounted) {
            // Show loading indicator
            ScaffoldMessenger.of(context).showSnackBar(
              const SnackBar(
                content: Row(
                  children: [
                    SizedBox(
                      width: 20,
                      height: 20,
                      child: CircularProgressIndicator(
                        strokeWidth: 2,
                        valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                      ),
                    ),
                    SizedBox(width: 12),
                    Text('Đang hủy đơn hàng...'),
                  ],
                ),
                duration: 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),
        ),
      ),
    );
  }
}
