import 'package:flutter/foundation.dart';

import '../domain/order.dart';
import '../domain/order_status.dart';
import 'get_orders.dart';

/// Controller that manages the orders workspace state, including
/// filtering by order status, free-text search, and order selection.
class OrdersController extends ChangeNotifier {
  final GetOrders _getOrders;

  OrdersController(this._getOrders);

  bool isLoading = false;
  Object? error;

  /// All orders returned by the repository (unfiltered).
  List<Order> _allOrders = [];

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

  /// The currently selected order for detail view.
  Order? selectedOrder;

  /// The active status filter label, or `null` for "all".
  ///
  /// Recognised values: `'pending'`, `'processing'`, `'shipped'`,
  /// `'delivered'`, `'cancelled'`.
  String? activeFilter;

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

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

    try {
      _allOrders = await _getOrders();
      _applyFilters();
      // Auto-select the first order if nothing is selected.
      selectedOrder ??= orders.isNotEmpty ? orders.first : null;
    } 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 order for detail view.
  void selectOrder(Order order) {
    selectedOrder = order;
    notifyListeners();
  }

  /// Attempts to select an order by ID. Returns `true` if found.
  bool selectById(String id) {
    final match = _allOrders.where((o) => o.id == id).firstOrNull;
    if (match != null) {
      selectedOrder = match;
      notifyListeners();
      return true;
    }
    return false;
  }

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

  void _applyFilters() {
    var result = _allOrders;

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

    // Free-text search on customer name and order ID
    if (searchQuery.isNotEmpty) {
      final q = searchQuery.toLowerCase();
      result = result.where((o) {
        return o.customerName.toLowerCase().contains(q) || o.id.toLowerCase().contains(q);
      }).toList();
    }

    orders = result;

    // Keep selection valid; clear if the selected order is no longer visible.
    if (selectedOrder != null && !orders.any((o) => o.id == selectedOrder!.id)) {
      selectedOrder = null;
    }
  }

  static OrderStatus? _parseStatus(String? filter) {
    if (filter == null) return null;
    switch (filter) {
      case 'pending':
        return OrderStatus.pending;
      case 'processing':
        return OrderStatus.processing;
      case 'shipped':
        return OrderStatus.shipped;
      case 'delivered':
        return OrderStatus.delivered;
      case 'cancelled':
        return OrderStatus.cancelled;
      default:
        return null;
    }
  }
}
