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

/// Full-screen inventory detail page for mobile.
///
/// Receives the shared [InventoryController] so that quantity adjustments are
/// immediately reflected in the list when the user pops back.
///
/// Wraps the shared [InventoryDetailPanel] from [feature_inventory] inside a
/// [Scaffold] with an [AppBar] showing the item name.
///
/// Unlike the web layout where feedback SnackBars are handled by the inventory
/// 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.
///
/// Quantity-adjust actions present a confirmation dialog before executing,
/// reducing accidental taps on touch screens.
class MobileInventoryDetailPage extends StatefulWidget {
  final InventoryController controller;

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

  const MobileInventoryDetailPage({super.key, required this.controller, this.onViewProduct});

  @override
  State<MobileInventoryDetailPage> createState() => _MobileInventoryDetailPageState();
}

class _MobileInventoryDetailPageState extends State<MobileInventoryDetailPage> {
  InventoryController 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;
      showInventoryActionSnackBar(context, result);
      if (result.success) HapticFeedback.mediumImpact();
    }
  }

  /// Handles the quantity adjustment flow.
  ///
  /// Shows the shared [showAdjustQuantityDialog] and, if confirmed, calls
  /// [InventoryController.adjustQuantity] with haptic feedback on success.
  Future<void> _handleAdjustQuantity() async {
    final item = _controller.selectedItem;
    if (item == null) return;

    final dialogResult = await showAdjustQuantityDialog(context, item);
    if (dialogResult == null) return;

    if (mounted) {
      await _controller.adjustQuantity(item.id, dialogResult.delta, dialogResult.reason);
      if (_controller.lastActionResult?.success == true) {
        HapticFeedback.lightImpact();
      }
    }
  }

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

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

        return Scaffold(
          appBar: AppBar(title: Text(item.name)),
          body: SafeArea(
            child: InventoryDetailPanel(
              item: item,
              isUpdating: _controller.isUpdating,
              onAdjustQuantity: _handleAdjustQuantity,
              onViewProduct: widget.onViewProduct != null
                  ? () => widget.onViewProduct!(item.sku)
                  : null,
            ),
          ),
        );
      },
    );
  }
}
