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

import 'mobile_product_detail_page.dart';

/// Mobile-optimized publishing workspace page.
///
/// Provides browsing, filtering, searching, sorting, and status changes
/// for the product publishing workflow on smaller screens. Tapping a
/// product pushes a full-screen detail page for viewing and editing.
///
/// Reuses the shared [ProductPublishingController] and all use cases
/// from [feature_wordpress] — no business logic is forked for mobile.
class MobilePublishingPage extends StatefulWidget {
  final ProductPublishingRepository repository;

  const MobilePublishingPage({super.key, required this.repository});

  @override
  State<MobilePublishingPage> createState() => _MobilePublishingPageState();
}

class _MobilePublishingPageState extends State<MobilePublishingPage> {
  late final ProductPublishingController _controller;
  late final TextEditingController _searchController;

  /// Whether the detail page is currently pushed on top.
  ///
  /// When `true`, action-result SnackBars are suppressed here because the
  /// detail page owns its own listener and shows feedback in its own
  /// [Scaffold]. Without this guard, SnackBars would be rendered behind
  /// the detail route and be invisible to the operator.
  bool _detailPageActive = false;

  @override
  void initState() {
    super.initState();
    _searchController = TextEditingController();

    final repo = widget.repository;
    _controller = ProductPublishingController(
      GetProductDrafts(repo),
      PublishProduct(repo),
      UpdateProductStatus(repo),
      UpdateProductPrice(repo),
      UpdateProductName(repo),
      UpdateProductDescription(repo),
      UpdateProductCategory(repo),
    );

    _controller.addListener(_onControllerChanged);
    _controller.load();
  }

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

  /// Handles action result feedback via SnackBars.
  ///
  /// Suppressed while the detail page is active — the detail page has its
  /// own listener that shows SnackBars using its local context.
  void _onControllerChanged() {
    if (_detailPageActive) return;

    final result = _controller.lastActionResult;
    if (result != null) {
      _controller.consumeActionResult();
      showStatusActionSnackBar(context, result);
    }

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

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

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

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

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, _) {
        if (_controller.isLoading) {
          return const KcLoadingState(message: 'Loading products…');
        }

        if (_controller.error != null) {
          return KcErrorState(message: 'Failed to load product drafts.', onRetry: _controller.load);
        }

        return Column(
          children: [
            _buildSearchBar(),
            _buildFilterChips(),
            _buildSortAndCount(),
            Expanded(child: _buildProductList()),
          ],
        );
      },
    );
  }

  /// Search bar with real-time filtering.
  Widget _buildSearchBar() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(KcSpacing.md, KcSpacing.sm, KcSpacing.md, KcSpacing.xs),
      child: TextField(
        controller: _searchController,
        decoration: InputDecoration(
          hintText: 'Search products…',
          prefixIcon: const Icon(Icons.search, size: 20),
          suffixIcon: _searchController.text.isNotEmpty
              ? IconButton(
                  icon: const Icon(Icons.clear, size: 20),
                  onPressed: () {
                    _searchController.clear();
                    _controller.setSearchQuery('');
                  },
                )
              : null,
          isDense: true,
          contentPadding: const EdgeInsets.symmetric(
            horizontal: KcSpacing.sm,
            vertical: KcSpacing.sm,
          ),
          border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
        ),
        onChanged: (query) {
          _controller.setSearchQuery(query);
          setState(() {}); // refresh clear button visibility
        },
      ),
    );
  }

  /// Horizontal scrollable filter chips for status filtering.
  Widget _buildFilterChips() {
    const filters = [
      (null, 'All'),
      ('draft', 'Draft'),
      ('pendingReview', 'Pending'),
      ('published', 'Published'),
      ('unpublished', 'Unpublished'),
    ];

    return SizedBox(
      height: 48,
      child: ListView.separated(
        scrollDirection: Axis.horizontal,
        padding: const EdgeInsets.symmetric(horizontal: KcSpacing.md),
        itemCount: filters.length,
        separatorBuilder: (_, _) => const SizedBox(width: KcSpacing.xs),
        itemBuilder: (context, index) {
          final (value, label) = filters[index];
          final isActive = _controller.activeFilter == value;
          return FilterChip(
            label: Text(label),
            selected: isActive,
            onSelected: (_) => _controller.setFilter(isActive ? null : value),
          );
        },
      ),
    );
  }

  /// Sort dropdown and product count row.
  Widget _buildSortAndCount() {
    final count = _controller.drafts.length;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: KcSpacing.md, vertical: KcSpacing.xs),
      child: Row(
        children: [
          Text(
            '$count ${count == 1 ? 'product' : 'products'}',
            style: Theme.of(context).textTheme.bodySmall?.copyWith(color: KcColors.neutral),
          ),
          const Spacer(),
          PopupMenuButton<ProductSortField>(
            icon: const Icon(Icons.sort, size: 20),
            tooltip: 'Sort',
            onSelected: (field) {
              if (field == _controller.activeSortField) {
                _controller.setSort(field, ascending: !_controller.sortAscending);
              } else {
                _controller.setSort(field, ascending: true);
              }
            },
            itemBuilder: (_) => [
              _sortMenuItem(ProductSortField.name, 'Name'),
              _sortMenuItem(ProductSortField.lastModified, 'Last Modified'),
              _sortMenuItem(ProductSortField.status, 'Status'),
            ],
          ),
        ],
      ),
    );
  }

  PopupMenuEntry<ProductSortField> _sortMenuItem(ProductSortField field, String label) {
    final isActive = _controller.activeSortField == field;
    return PopupMenuItem(
      value: field,
      child: Row(
        children: [
          Expanded(
            child: Text(
              label,
              style: isActive ? const TextStyle(fontWeight: FontWeight.bold) : null,
            ),
          ),
          if (isActive)
            Icon(_controller.sortAscending ? Icons.arrow_upward : Icons.arrow_downward, size: 16),
        ],
      ),
    );
  }

  /// Scrollable product list using compact cards.
  Widget _buildProductList() {
    final drafts = _controller.drafts;

    if (drafts.isEmpty) {
      return KcEmptyState(
        icon: Icons.search_off,
        message: _controller.searchQuery.isNotEmpty || _controller.activeFilter != null
            ? 'No products match your criteria.'
            : 'No product drafts available.',
      );
    }

    return RefreshIndicator(
      onRefresh: _controller.load,
      child: ListView.separated(
        padding: const EdgeInsets.symmetric(horizontal: KcSpacing.md),
        itemCount: drafts.length,
        separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.xs),
        itemBuilder: (context, index) {
          final draft = drafts[index];
          return SizedBox(
            height: 72,
            child: ProductDraftCard(
              draft: draft,
              isSelected: draft.id == _controller.selectedDraft?.id,
              isCompact: true,
              isStale: _controller.isStale(draft),
              onTap: () => _navigateToDetail(draft),
            ),
          );
        },
      ),
    );
  }

  /// Navigates to the full-screen product detail page.
  ///
  /// Sets [_detailPageActive] to suppress SnackBars on this page while the
  /// detail page is visible. Cleared when the detail page pops back.
  void _navigateToDetail(ProductDraft draft) {
    _controller.selectDraft(draft);
    setState(() => _detailPageActive = true);
    Navigator.of(context)
        .push(
          MaterialPageRoute<void>(builder: (_) => MobileProductDetailPage(controller: _controller)),
        )
        .then((_) {
          if (mounted) setState(() => _detailPageActive = false);
        });
  }
}
