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

import '../../domain/order.dart';
import '../../domain/order_status.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, order total,
/// order notes, and action buttons for status update and note addition.
class OrderDetailPanel extends StatelessWidget {
  final Order order;

  /// Whether a write operation is currently in progress.
  final bool isUpdating;

  /// Called when the operator selects a new status from the dropdown.
  final void Function(OrderStatus newStatus)? onUpdateStatus;

  /// Called when the operator taps "Add Note".
  final VoidCallback? onAddNote;

  /// 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.isUpdating = false,
    this.onUpdateStatus,
    this.onAddNote,
    this.onViewProduct,
    this.onViewInventory,
  });

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

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

          // ── Customer info ──────────────────────────────────────────
          KcSectionHeader(title: 'Customer'),
          const SizedBox(height: KcSpacing.sm),
          _MetadataRow(label: 'Name', value: order.customerName),
          _MetadataRow(label: 'Email', value: order.customerEmail),
          if (order.customerPhone != null)
            _MetadataRow(label: 'Phone', value: order.customerPhone!),
          _MetadataRow(label: 'Order Date', value: _formatDate(order.orderDate)),
          const SizedBox(height: KcSpacing.md),

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

          const Divider(),
          const SizedBox(height: KcSpacing.md),

          // ── Line items ─────────────────────────────────────────────
          KcSectionHeader(title: 'Items'),
          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),
              ),
            ],
          ),

          // ── Order notes ────────────────────────────────────────────
          if (order.orderNotes.isNotEmpty) ...[
            const SizedBox(height: KcSpacing.md),
            const Divider(),
            const SizedBox(height: KcSpacing.md),
            KcSectionHeader(title: 'Notes'),
            const SizedBox(height: KcSpacing.sm),
            ...order.orderNotes.map(
              (note) => Padding(
                padding: const EdgeInsets.only(bottom: KcSpacing.sm),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Icon(Icons.notes, size: 16, color: KcColors.neutral),
                    const SizedBox(width: KcSpacing.xs),
                    Expanded(child: Text(note, style: theme.textTheme.bodyMedium)),
                  ],
                ),
              ),
            ),
          ],

          const SizedBox(height: KcSpacing.xl),

          // ── Actions ────────────────────────────────────────────────
          if (isUpdating)
            const Center(child: CircularProgressIndicator())
          else
            Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                // Status update dropdown
                if (onUpdateStatus != null) ...[
                  Text('Update Status', style: theme.textTheme.labelLarge),
                  const SizedBox(height: KcSpacing.xs),
                  _StatusDropdown(currentStatus: order.status, onChanged: onUpdateStatus!),
                  const SizedBox(height: KcSpacing.sm),
                ],

                // Add note button
                if (onAddNote != null)
                  OutlinedButton.icon(
                    onPressed: onAddNote,
                    icon: const Icon(Icons.note_add_outlined, size: 18),
                    label: const Text('Add Note'),
                  ),
              ],
            ),
        ],
      ),
    );
  }

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

// ── Status dropdown ────────────────────────────────────────────────────────────

class _StatusDropdown extends StatelessWidget {
  final OrderStatus currentStatus;
  final void Function(OrderStatus) onChanged;

  const _StatusDropdown({required this.currentStatus, required this.onChanged});

  static const _statuses = [
    (label: 'Pending', value: OrderStatus.pending),
    (label: 'Processing', value: OrderStatus.processing),
    (label: 'Shipped', value: OrderStatus.shipped),
    (label: 'Delivered', value: OrderStatus.delivered),
    (label: 'Cancelled', value: OrderStatus.cancelled),
  ];

  @override
  Widget build(BuildContext context) {
    return DropdownButtonFormField<OrderStatus>(
      initialValue: currentStatus,
      decoration: const InputDecoration(
        border: OutlineInputBorder(),
        isDense: true,
        contentPadding: EdgeInsets.symmetric(horizontal: KcSpacing.md, vertical: KcSpacing.sm),
      ),
      items: _statuses.map((s) => DropdownMenuItem(value: s.value, child: Text(s.label))).toList(),
      onChanged: (value) {
        if (value != null && value != currentStatus) {
          onChanged(value);
        }
      },
    );
  }
}

// ── Private helpers ────────────────────────────────────────────────────────────

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)),
        ],
      ),
    );
  }
}
