import 'package:flutter/foundation.dart';
import '../domain/inventory_item.dart';
import '../domain/inventory_status.dart';
import 'get_inventory_items.dart';

/// Controller that manages the inventory workspace state, including
/// filtering by status, free-text search, and item selection.
class InventoryController extends ChangeNotifier {
  final GetInventoryItems _getInventoryItems;

  InventoryController(this._getInventoryItems);

  bool isLoading = false;
  Object? error;

  /// All items returned by the repository (unfiltered).
  List<InventoryItem> _allItems = [];

  /// The currently visible items after applying [activeFilter] and [searchQuery].
  List<InventoryItem> items = [];

  /// The currently selected item, if any.
  InventoryItem? selectedItem;

  /// The active status filter label, or `null` for "all".
  ///
  /// Recognised values: `'inStock'`, `'lowStock'`, `'outOfStock'`, `'draft'`.
  String? activeFilter;

  /// The current free-text search query applied to name / SKU.
  String searchQuery = '';

  /// Loads all inventory items and applies any current filter / search.
  Future<void> load() async {
    isLoading = true;
    error = null;
    notifyListeners();

    try {
      _allItems = await _getInventoryItems();
      _applyFilters();
    } catch (e) {
      error = e;
    } finally {
      isLoading = false;
      notifyListeners();
    }
  }

  /// Sets the status filter and recomputes the visible list.
  void setFilter(String? filter) {
    activeFilter = filter;
    _applyFilters();
    notifyListeners();
  }

  /// Sets the search query and recomputes the visible list.
  void setSearchQuery(String query) {
    searchQuery = query;
    _applyFilters();
    notifyListeners();
  }

  /// Selects an item for detail view / highlight.
  void selectItem(InventoryItem item) {
    selectedItem = item;
    notifyListeners();
  }

  /// Attempts to select an item by SKU. Returns `true` if found.
  bool selectBySku(String sku) {
    final match = _allItems.where((i) => i.sku == sku).firstOrNull;
    if (match != null) {
      selectedItem = match;
      notifyListeners();
      return true;
    }
    return false;
  }

  // ── Private helpers ────────────────────────────────────────────────────

  void _applyFilters() {
    var result = _allItems;

    // Status filter
    final status = _parseStatus(activeFilter);
    if (status != null) {
      result = result.where((i) => i.status == status).toList();
    }

    // Free-text search on name and SKU
    if (searchQuery.isNotEmpty) {
      final q = searchQuery.toLowerCase();
      result = result.where((i) {
        return i.name.toLowerCase().contains(q) || i.sku.toLowerCase().contains(q);
      }).toList();
    }

    items = result;

    // Keep selection valid; clear if the selected item is no longer visible.
    if (selectedItem != null && !items.contains(selectedItem)) {
      selectedItem = null;
    }
  }

  static InventoryStatus? _parseStatus(String? filter) {
    if (filter == null) return null;
    switch (filter) {
      case 'inStock':
        return InventoryStatus.inStock;
      case 'lowStock':
        return InventoryStatus.lowStock;
      case 'outOfStock':
        return InventoryStatus.outOfStock;
      case 'draft':
        return InventoryStatus.draft;
      default:
        return null;
    }
  }
}
