/// Order Summary Section Widget
///
/// Displays cart items with conversion details and price breakdown.
/// Matches checkout.html design with product name on line 1, conversion on line 2.
library;

import 'package:flutter/material.dart';
import 'package:worker/core/constants/ui_constants.dart';
import 'package:worker/core/theme/colors.dart';

/// Order Summary Section
///
/// Shows order items with conversion details, subtotal, discount, shipping, and total.
class OrderSummarySection extends StatelessWidget {
  final List<Map<String, dynamic>> cartItems;
  final double subtotal;
  final double discount;
  final double shipping;
  final double total;

  const OrderSummarySection({
    super.key,
    required this.cartItems,
    required this.subtotal,
    required this.discount,
    required this.shipping,
    required this.total,
  });

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

    return Container(
      margin: const EdgeInsets.symmetric(horizontal: AppSpacing.md),
      padding: const EdgeInsets.all(AppSpacing.md),
      decoration: BoxDecoration(
        color: colorScheme.surface,
        borderRadius: BorderRadius.circular(AppRadius.card),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 8,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Section Title
          Text(
            'Tóm tắt đơn hàng',
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.bold,
              color: colorScheme.onSurface,
            ),
          ),

          const SizedBox(height: AppSpacing.md),

          // Cart Items with conversion details
          ...cartItems.map((item) => _buildCartItemWithConversion(context, item)),

          const Divider(height: 32),

          // Subtotal
          _buildSummaryRow(context, 'Tạm tính', subtotal),
          const SizedBox(height: 8),

          // Member Tier Discount (Diamond 15%)
          _buildSummaryRow(context, 'Giảm giá Diamond', -discount, isDiscount: true),
          const SizedBox(height: 8),

          // Shipping
          _buildSummaryRow(context, 'Phí vận chuyển', shipping, isFree: shipping == 0),

          const Divider(height: 24),

          // Total
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                'Tổng thanh toán',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                  color: colorScheme.onSurface,
                ),
              ),
              Text(
                _formatCurrency(total),
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: colorScheme.primary,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// Build cart item with conversion details on two lines
  Widget _buildCartItemWithConversion(BuildContext context, Map<String, dynamic> item) {
    final colorScheme = Theme.of(context).colorScheme;

    // Get real conversion data from CartItemData
    final quantity = item['quantity'] as double;
    final quantityConverted = item['quantityConverted'] as double;
    final boxes = item['boxes'] as int;
    final price = item['price'] as double;

    return Padding(
      padding: const EdgeInsets.only(bottom: 12),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Product info (left side)
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Line 1: Product name
                Text(
                  item['name'] as String,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.w500,
                    color: colorScheme.onSurface,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                // Line 2: Conversion details (muted text)
                Text(
                  '${quantity.toStringAsFixed(2)} m² ($boxes viên / ${quantityConverted.toStringAsFixed(2)} m²)',
                  style: TextStyle(
                    fontSize: 13,
                    color: colorScheme.onSurfaceVariant,
                  ),
                ),
              ],
            ),
          ),

          const SizedBox(width: 12),

          // Price (right side) - using converted quantity for accurate billing
          Text(
            _formatCurrency(price * quantityConverted),
            style: TextStyle(
              fontSize: 14,
              fontWeight: FontWeight.w600,
              color: colorScheme.onSurface,
            ),
          ),
        ],
      ),
    );
  }

  /// Build summary row
  Widget _buildSummaryRow(
    BuildContext context,
    String label,
    double amount, {
    bool isDiscount = false,
    bool isFree = false,
  }) {
    final colorScheme = Theme.of(context).colorScheme;

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(fontSize: 14, color: colorScheme.onSurfaceVariant),
        ),
        Text(
          isFree ? 'Miễn phí' : _formatCurrency(amount),
          style: TextStyle(
            fontSize: 14,
            fontWeight: FontWeight.w500,
            color: isDiscount ? AppColors.success : colorScheme.onSurface,
          ),
        ),
      ],
    );
  }

  /// Format currency
  String _formatCurrency(double amount) {
    return '${amount.abs().toStringAsFixed(0).replaceAllMapped(RegExp(r'(\d)(?=(\d{3})+(?!\d))'), (Match m) => '${m[1]}.')}đ';
  }
}
