import 'package:feature_orders/feature_orders.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// Full-screen order detail page for mobile.
///
/// Receives the shared [OrdersController] so that status updates and note
/// additions are immediately reflected in the list when the user pops back.
///
/// Wraps the shared [OrderDetailPanel] from [feature_orders] inside a
/// [Scaffold] with an [AppBar] showing the order ID.
///
/// Unlike the web layout where feedback SnackBars are handled by the orders
/// page wrapper, this detail page is pushed via [Navigator] and owns its own
/// [Scaffold]. It therefore attaches its own listener to the controller and
/// shows action-result SnackBars using its local [BuildContext], ensuring
/// they are visible on the active screen.
///
/// Status-change actions present a confirmation dialog before executing,
/// reducing accidental taps on touch screens.
class MobileOrderDetailPage extends StatefulWidget {
  final OrdersController controller;

  /// 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 MobileOrderDetailPage({
    super.key,
    required this.controller,
    this.onViewProduct,
    this.onViewInventory,
  });

  @override
  State<MobileOrderDetailPage> createState() => _MobileOrderDetailPageState();
}

class _MobileOrderDetailPageState extends State<MobileOrderDetailPage> {
  OrdersController get _controller => widget.controller;

  @override
  void initState() {
    super.initState();
    _controller.addListener(_onControllerChanged);
  }

  @override
  void dispose() {
    _controller.removeListener(_onControllerChanged);
    super.dispose();
  }

  /// Handles action result feedback via SnackBars on this detail page.
  ///
  /// Because this page is pushed on top of the list page via [Navigator],
  /// the list page's listener cannot reliably display SnackBars (they
  /// would appear behind this route). This listener ensures feedback is
  /// always visible to the operator.
  void _onControllerChanged() {
    if (!mounted) return;

    final result = _controller.lastActionResult;
    if (result != null && !_controller.isUpdating) {
      _controller.lastActionResult = null;
      showOrderActionSnackBar(context, result);
      if (result.success) HapticFeedback.mediumImpact();
    }
  }

  /// Shows a confirmation dialog before executing a status change.
  ///
  /// Returns `true` if the user confirmed, `false` otherwise.
  Future<bool> _confirmStatusChange({
    required String orderId,
    required OrderStatus newStatus,
  }) async {
    final label = _statusLabel(newStatus);
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('Update to $label?'),
        content: Text('Change order $orderId status to "$label"?'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('Cancel'),
          ),
          FilledButton(onPressed: () => Navigator.of(context).pop(true), child: Text('Update')),
        ],
      ),
    );
    return confirmed ?? false;
  }

  /// Handles a status update with confirmation dialog.
  Future<void> _handleUpdateStatus(OrderStatus newStatus) async {
    final order = _controller.selectedOrder;
    if (order == null) return;

    final confirmed = await _confirmStatusChange(orderId: order.id, newStatus: newStatus);
    if (confirmed && mounted) {
      await _controller.updateOrderStatus(order.id, newStatus);
    }
  }

  /// Handles adding a note via the shared dialog.
  Future<void> _handleAddNote() async {
    final order = _controller.selectedOrder;
    if (order == null) return;

    final dialogResult = await showAddNoteDialog(context);
    if (dialogResult == null) return;

    if (mounted) {
      await _controller.addOrderNote(order.id, dialogResult.note);
      if (_controller.lastActionResult?.success == true) {
        HapticFeedback.lightImpact();
      }
    }
  }

  static String _statusLabel(OrderStatus status) {
    switch (status) {
      case OrderStatus.pending:
        return 'Pending';
      case OrderStatus.processing:
        return 'Processing';
      case OrderStatus.shipped:
        return 'Shipped';
      case OrderStatus.delivered:
        return 'Delivered';
      case OrderStatus.cancelled:
        return 'Cancelled';
      case OrderStatus.onHold:
        return 'On Hold';
      case OrderStatus.refunded:
        return 'Refunded';
      case OrderStatus.failed:
        return 'Failed';
    }
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        final order = _controller.selectedOrder;

        // If the order was removed or deselected, pop back.
        if (order == null) {
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (context.mounted) Navigator.of(context).pop();
          });
          return const Scaffold(body: Center(child: CircularProgressIndicator()));
        }

        return Scaffold(
          appBar: AppBar(title: Text('Order ${order.id}')),
          body: SafeArea(
            child: OrderDetailPanel(
              order: order,
              isUpdating: _controller.isUpdating,
              onUpdateStatus: _handleUpdateStatus,
              onAddNote: _handleAddNote,
              onViewProduct: widget.onViewProduct,
              onViewInventory: widget.onViewInventory,
            ),
          ),
        );
      },
    );
  }
}
