import 'package:design_system/design_system.dart';
import 'package:flutter/material.dart';

import '../../domain/order.dart';
import 'order_status_chip.dart';

/// A detail panel that shows the full information for the selected [Order].
///
/// Includes customer info, shipping address, line items table, and order total.
class OrderDetailPanel extends StatelessWidget {
  final Order order;

  /// Optional callback to navigate to the Products page for a given SKU.
  final void Function(String sku)? onViewProduct;

  /// Optional callback to navigate to the Inventory page for a given SKU.
  final void Function(String sku)? onViewInventory;

  const OrderDetailPanel({
    super.key,
    required this.order,
    this.onViewProduct,
    this.onViewInventory,
  });

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

    return KcCard(
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // ── Header ─────────────────────────────────────────────────
            Row(
              children: [
                Expanded(child: Text('Order ${order.id}', style: theme.textTheme.headlineMedium)),
                const SizedBox(width: KcSpacing.sm),
                OrderStatusChip(status: order.status),
              ],
            ),
            const SizedBox(height: KcSpacing.md),

            // ── Customer info ──────────────────────────────────────────
            Text('Customer', style: theme.textTheme.titleLarge),
            const SizedBox(height: KcSpacing.sm),
            _MetadataRow(label: 'Name', value: order.customerName),
            _MetadataRow(label: 'Email', value: order.customerEmail),
            _MetadataRow(label: 'Order Date', value: _formatDate(order.orderDate)),
            const SizedBox(height: KcSpacing.md),

            // ── Shipping address ───────────────────────────────────────
            Text('Shipping Address', style: theme.textTheme.titleLarge),
            const SizedBox(height: KcSpacing.sm),
            Text(order.shippingAddress, style: theme.textTheme.bodyLarge),
            const SizedBox(height: KcSpacing.md),

            // ── Line items ─────────────────────────────────────────────
            Text('Items', style: theme.textTheme.titleLarge),
            const SizedBox(height: KcSpacing.sm),
            ...order.items.map(
              (item) => Padding(
                padding: const EdgeInsets.symmetric(vertical: KcSpacing.xs),
                child: Row(
                  children: [
                    Expanded(
                      flex: 3,
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(item.productName, style: theme.textTheme.bodyMedium),
                          Text(
                            'SKU: ${item.sku}',
                            style: theme.textTheme.bodySmall?.copyWith(color: KcColors.neutral),
                          ),
                          if (onViewProduct != null || onViewInventory != null)
                            Padding(
                              padding: const EdgeInsets.only(top: KcSpacing.xs),
                              child: Wrap(
                                spacing: KcSpacing.sm,
                                children: [
                                  if (onViewProduct != null)
                                    GestureDetector(
                                      onTap: () => onViewProduct!(item.sku),
                                      child: Text(
                                        'View Product',
                                        style: theme.textTheme.bodySmall?.copyWith(
                                          color: KcColors.denimBlue,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                  if (onViewInventory != null)
                                    GestureDetector(
                                      onTap: () => onViewInventory!(item.sku),
                                      child: Text(
                                        'View Inventory',
                                        style: theme.textTheme.bodySmall?.copyWith(
                                          color: KcColors.denimBlue,
                                          fontWeight: FontWeight.w600,
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ),
                        ],
                      ),
                    ),
                    SizedBox(
                      width: 40,
                      child: Text(
                        'x${item.quantity}',
                        style: theme.textTheme.bodyMedium,
                        textAlign: TextAlign.center,
                      ),
                    ),
                    SizedBox(
                      width: 80,
                      child: Text(
                        '\$${item.lineTotal.toStringAsFixed(2)}',
                        style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w600),
                        textAlign: TextAlign.end,
                      ),
                    ),
                  ],
                ),
              ),
            ),
            const Divider(height: KcSpacing.lg),

            // ── Total ──────────────────────────────────────────────────
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Text('Total: ', style: theme.textTheme.titleLarge),
                Text(
                  '\$${order.total.toStringAsFixed(2)}',
                  style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w700),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  static String _formatDate(DateTime date) {
    return '${date.year}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}';
  }
}

class _MetadataRow extends StatelessWidget {
  final String label;
  final String value;

  const _MetadataRow({required this.label, required this.value});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: KcSpacing.xs),
      child: Row(
        children: [
          SizedBox(
            width: 120,
            child: Text(
              label,
              style: Theme.of(context).textTheme.bodyMedium?.copyWith(
                color: KcColors.neutral,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
          Expanded(child: Text(value, style: Theme.of(context).textTheme.bodyMedium)),
        ],
      ),
    );
  }
}
