/// Providers: Orders
///
/// Riverpod providers for managing orders state.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/core/database/models/enums.dart';
import 'package:worker/features/orders/data/datasources/orders_local_datasource.dart';
import 'package:worker/features/orders/data/models/order_model.dart';

part 'orders_provider.g.dart';

/// Orders Local Data Source Provider
@riverpod
OrdersLocalDataSource ordersLocalDataSource(Ref ref) {
  return OrdersLocalDataSource();
}

/// Orders Provider
///
/// Provides list of all orders from local data source.
@riverpod
class Orders extends _$Orders {
  @override
  Future<List<OrderModel>> build() async {
    return await ref.read(ordersLocalDataSourceProvider).getAllOrders();
  }

  /// Refresh orders
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await ref.read(ordersLocalDataSourceProvider).getAllOrders();
    });
  }
}

/// Selected Order Status Provider
///
/// Tracks the currently selected order status filter.
/// null means "All" orders.
@riverpod
class SelectedOrderStatus extends _$SelectedOrderStatus {
  @override
  OrderStatus? build() {
    return null; // Default: show all orders
  }

  /// Select a status filter
  void selectStatus(OrderStatus? status) {
    state = status;
  }

  /// Clear selection (show all)
  void clearSelection() {
    state = null;
  }
}

/// Order Search Query Provider
///
/// Tracks the current search query for order numbers.
@riverpod
class OrderSearchQuery extends _$OrderSearchQuery {
  @override
  String build() {
    return '';
  }

  /// Update search query
  void updateQuery(String query) {
    state = query;
  }

  /// Clear search query
  void clearQuery() {
    state = '';
  }
}

/// Filtered Orders Provider
///
/// Filters orders by selected status and search query.
@riverpod
Future<List<OrderModel>> filteredOrders(Ref ref) async {
  final ordersAsync = ref.watch(ordersProvider);
  final selectedStatus = ref.watch(selectedOrderStatusProvider);
  final searchQuery = ref.watch(orderSearchQueryProvider);

  return ordersAsync.when(
    data: (orders) {
      var filtered = orders;

      // Filter by status
      if (selectedStatus != null) {
        filtered = filtered
            .where((order) => order.status == selectedStatus)
            .toList();
      }

      // Filter by search query
      if (searchQuery.isNotEmpty) {
        filtered = filtered
            .where(
              (order) => order.orderNumber.toLowerCase().contains(
                searchQuery.toLowerCase(),
              ),
            )
            .toList();
      }

      // Sort by creation date (newest first)
      filtered.sort((a, b) => b.createdAt.compareTo(a.createdAt));

      return filtered;
    },
    loading: () => [],
    error: (error, stack) => [],
  );
}

/// Orders Count by Status Provider
///
/// Returns count of orders for each status.
@riverpod
Future<Map<OrderStatus, int>> ordersCountByStatus(Ref ref) async {
  final ordersAsync = ref.watch(ordersProvider);

  return ordersAsync.when(
    data: (orders) {
      final counts = <OrderStatus, int>{};

      for (final status in OrderStatus.values) {
        counts[status] = orders.where((order) => order.status == status).length;
      }

      return counts;
    },
    loading: () => {},
    error: (error, stack) => {},
  );
}

/// Total Orders Count Provider
@riverpod
Future<int> totalOrdersCount(Ref ref) async {
  final ordersAsync = ref.watch(ordersProvider);

  return ordersAsync.when(
    data: (orders) => orders.length,
    loading: () => 0,
    error: (error, stack) => 0,
  );
}
