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

import 'mobile_order_detail_page.dart';

/// Mobile-optimized orders workspace page.
///
/// Provides browsing, filtering, and searching for orders on smaller screens.
/// Tapping an order pushes a full-screen detail page for viewing, status
/// updates, and note additions.
///
/// Reuses the shared [OrdersController] and all use cases from
/// [feature_orders] — no business logic is forked for mobile.
class MobileOrdersPage extends StatefulWidget {
  final OrdersRepository repository;

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

  @override
  State<MobileOrdersPage> createState() => _MobileOrdersPageState();
}

class _MobileOrdersPageState extends State<MobileOrdersPage> {
  late final OrdersController _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 = OrdersController(
      GetOrders(repo),
      updateOrderStatus: UpdateOrderStatus(repo),
      addOrderNote: AddOrderNote(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.isUpdating) {
      _controller.lastActionResult = null;
      showOrderActionSnackBar(context, result);
    }
  }

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

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

        return Column(
          children: [
            _buildSearchBar(),
            _buildFilterChips(),
            _buildOrderCount(),
            Expanded(child: _buildOrderList()),
          ],
        );
      },
    );
  }

  /// 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 by customer or order ID…',
          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'),
      ('pending', 'Pending'),
      ('processing', 'Processing'),
      ('shipped', 'Shipped'),
      ('delivered', 'Delivered'),
      ('cancelled', 'Cancelled'),
    ];

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

  /// Order count row.
  Widget _buildOrderCount() {
    final count = _controller.orders.length;
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: KcSpacing.md, vertical: KcSpacing.xs),
      child: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          '$count ${count == 1 ? 'order' : 'orders'}',
          style: Theme.of(context).textTheme.bodySmall?.copyWith(color: KcColors.neutral),
        ),
      ),
    );
  }

  /// Scrollable order list using compact cards.
  Widget _buildOrderList() {
    final orders = _controller.orders;

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

    return RefreshIndicator(
      onRefresh: _controller.load,
      child: ListView.separated(
        padding: const EdgeInsets.symmetric(horizontal: KcSpacing.md),
        itemCount: orders.length,
        separatorBuilder: (_, _) => const SizedBox(height: KcSpacing.xs),
        itemBuilder: (context, index) {
          final order = orders[index];
          return SizedBox(
            height: 160,
            child: OrderCard(
              order: order,
              isSelected: order.id == _controller.selectedOrder?.id,
              onTap: () => _navigateToDetail(order),
            ),
          );
        },
      ),
    );
  }

  /// Navigates to the full-screen order 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(Order order) {
    _controller.selectOrder(order);
    setState(() => _detailPageActive = true);
    Navigator.of(context)
        .push(
          MaterialPageRoute<void>(
            builder: (_) => MobileOrderDetailPage(
              controller: _controller,
              onViewProduct: widget.onViewProduct,
              onViewInventory: widget.onViewInventory,
            ),
          ),
        )
        .then((_) {
          if (mounted) setState(() => _detailPageActive = false);
        });
  }
}
