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

import 'mobile_inventory_detail_page.dart';

/// Mobile-optimized inventory workspace page.
///
/// Provides browsing, filtering, and searching for inventory items on smaller
/// screens. Tapping an item pushes a full-screen detail page for viewing and
/// quantity adjustment.
///
/// Reuses the shared [InventoryController] and all use cases from
/// [feature_inventory] — no business logic is forked for mobile.
class MobileInventoryPage extends StatefulWidget {
  final InventoryRepository repository;

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

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

  @override
  State<MobileInventoryPage> createState() => _MobileInventoryPageState();
}

class _MobileInventoryPageState extends State<MobileInventoryPage> {
  late final InventoryController _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 = InventoryController(
      GetInventoryItems(repo),
      AdjustInventoryQuantity(repo),
      CreateInventoryItem(repo),
      UpdateInventoryItem(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;
      showInventoryActionSnackBar(context, result);
    }
  }

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

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

        return Column(
          children: [
            _buildSearchBar(),
            _buildFilterChips(),
            _buildItemCount(),
            Expanded(child: _buildItemList()),
          ],
        );
      },
    );
  }

  /// 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 name or SKU…',
          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'),
      ('inStock', 'In Stock'),
      ('lowStock', 'Low Stock'),
      ('outOfStock', 'Out of Stock'),
      ('draft', 'Draft'),
    ];

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

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

  /// Scrollable inventory list using compact cards.
  Widget _buildItemList() {
    final items = _controller.items;

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

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

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

// ── Compact mobile inventory card ──────────────────────────────────────────────

/// A compact card for displaying an [InventoryItem] in the mobile list.
///
/// Shows name, SKU, status chip, and quantity at a glance.
class _MobileInventoryCard extends StatelessWidget {
  final InventoryItem item;
  final bool isSelected;
  final VoidCallback onTap;

  const _MobileInventoryCard({required this.item, required this.isSelected, required this.onTap});

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);

    return Card(
      elevation: isSelected ? 3 : 1,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
        side: isSelected ? BorderSide(color: theme.colorScheme.primary, width: 2) : BorderSide.none,
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(8),
        child: Padding(
          padding: const EdgeInsets.all(KcSpacing.sm),
          child: Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Text(
                      item.name,
                      style: theme.textTheme.titleSmall,
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      'SKU: ${item.sku}',
                      style: theme.textTheme.bodySmall?.copyWith(color: KcColors.neutral),
                    ),
                    const SizedBox(height: KcSpacing.xs),
                    InventoryStatusChip(status: item.status),
                  ],
                ),
              ),
              const SizedBox(width: KcSpacing.sm),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    '${item.quantityOnHand}',
                    style: theme.textTheme.headlineSmall?.copyWith(fontWeight: FontWeight.bold),
                  ),
                  Text(
                    'on hand',
                    style: theme.textTheme.bodySmall?.copyWith(color: KcColors.neutral),
                  ),
                ],
              ),
              const SizedBox(width: KcSpacing.xs),
              const Icon(Icons.chevron_right, color: KcColors.neutral),
            ],
          ),
        ),
      ),
    );
  }
}
