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

/// Full-screen product detail page for mobile.
///
/// Receives the shared [ProductPublishingController] so that edits
/// (name, price, description, category, status) are immediately
/// reflected in the list when the user pops back.
///
/// Wraps the shared [ProductPreviewPanel] from [feature_wordpress]
/// inside a [Scaffold] with an [AppBar] showing the product name.
///
/// Unlike the web layout where feedback SnackBars are handled by the
/// publishing 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 (publish / move-to-draft) present a
/// confirmation dialog before executing, reducing accidental taps on
/// touch screens.
class MobileProductDetailPage extends StatefulWidget {
  final ProductPublishingController controller;

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

  @override
  State<MobileProductDetailPage> createState() => _MobileProductDetailPageState();
}

class _MobileProductDetailPageState extends State<MobileProductDetailPage> {
  ProductPublishingController 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.consumeActionResult();
      showStatusActionSnackBar(context, result);
      if (result.success) HapticFeedback.mediumImpact();
    }

    final priceResult = _controller.lastPriceResult;
    if (priceResult != null) {
      _controller.consumePriceResult();
      showPriceActionSnackBar(context, priceResult);
      if (priceResult.success) HapticFeedback.lightImpact();
    }

    final nameResult = _controller.lastNameResult;
    if (nameResult != null) {
      _controller.consumeNameResult();
      showNameActionSnackBar(context, nameResult);
      if (nameResult.success) HapticFeedback.lightImpact();
    }

    final descriptionResult = _controller.lastDescriptionResult;
    if (descriptionResult != null) {
      _controller.consumeDescriptionResult();
      showDescriptionActionSnackBar(context, descriptionResult);
      if (descriptionResult.success) HapticFeedback.lightImpact();
    }

    final categoryResult = _controller.lastCategoryResult;
    if (categoryResult != null) {
      _controller.consumeCategoryResult();
      showCategoryActionSnackBar(context, categoryResult);
      if (categoryResult.success) HapticFeedback.lightImpact();
    }
  }

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

  /// Publishes the product after confirmation.
  Future<void> _handlePublish(String id, String name) async {
    final confirmed = await _confirmStatusChange(
      productName: name,
      actionLabel: 'Publish',
      description: 'Publish "$name" to the store? This will make it visible to customers.',
    );
    if (confirmed && mounted) {
      _controller.updateStatus(id, PublishStatus.published);
    }
  }

  /// Moves the product to draft after confirmation.
  Future<void> _handleMoveToDraft(String id, String name) async {
    final confirmed = await _confirmStatusChange(
      productName: name,
      actionLabel: 'Move to Draft',
      description: 'Move "$name" back to draft? This will remove it from the store.',
    );
    if (confirmed && mounted) {
      _controller.updateStatus(id, PublishStatus.draft);
    }
  }

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

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

        return Scaffold(
          appBar: AppBar(title: Text(draft.name)),
          body: SafeArea(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: ProductPreviewPanel(
                draft: draft,
                isUpdating: _controller.isUpdating(draft.id),
                onPublish: () => _handlePublish(draft.id, draft.name),
                onMoveToDraft: () => _handleMoveToDraft(draft.id, draft.name),
                onPriceChanged: (price) => _controller.updatePrice(draft.id, price),
                onNameChanged: (name) => _controller.updateName(draft.id, name),
                onDescriptionChanged: (desc) => _controller.updateDescription(draft.id, desc),
                onCategoryChanged: (cat) => _controller.updateCategory(draft.id, cat),
              ),
            ),
          ),
        );
      },
    );
  }
}
