/// Providers: Points History
///
/// Riverpod providers for managing points history state.
library;

import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:worker/features/loyalty/data/datasources/points_history_local_datasource.dart';
import 'package:worker/features/loyalty/data/models/loyalty_point_entry_model.dart';

part 'points_history_provider.g.dart';

/// Points History Filter State
class PointsHistoryFilter {
  const PointsHistoryFilter({
    this.startDate,
    this.endDate,
  });

  final DateTime? startDate;
  final DateTime? endDate;

  PointsHistoryFilter copyWith({
    DateTime? startDate,
    DateTime? endDate,
    bool clearStartDate = false,
    bool clearEndDate = false,
  }) {
    return PointsHistoryFilter(
      startDate: clearStartDate ? null : (startDate ?? this.startDate),
      endDate: clearEndDate ? null : (endDate ?? this.endDate),
    );
  }
}

/// Points History Filter Provider
@riverpod
class PointsHistoryFilterNotifier extends _$PointsHistoryFilterNotifier {
  @override
  PointsHistoryFilter build() {
    // Default: current year
    final now = DateTime.now();
    return PointsHistoryFilter(
      startDate: DateTime(now.year, 1, 1),
      endDate: DateTime(now.year, 12, 31),
    );
  }

  void setDateRange(DateTime? start, DateTime? end) {
    state = PointsHistoryFilter(startDate: start, endDate: end);
  }

  void setStartDate(DateTime? date) {
    state = state.copyWith(startDate: date);
  }

  void setEndDate(DateTime? date) {
    state = state.copyWith(endDate: date);
  }

  void clearFilter() {
    state = const PointsHistoryFilter();
  }
}

/// Points History Local Data Source Provider
@riverpod
PointsHistoryLocalDataSource pointsHistoryLocalDataSource(Ref ref) {
  return PointsHistoryLocalDataSource();
}

/// Points History Provider
///
/// Provides list of all points history entries from local data source.
@riverpod
class PointsHistory extends _$PointsHistory {
  @override
  Future<List<LoyaltyPointEntryModel>> build() async {
    final datasource = ref.read(pointsHistoryLocalDataSourceProvider);

    // Seed mock data on first load
    final entries = await datasource.getAllEntries();
    if (entries.isEmpty) {
      await datasource.seedMockEntries();
      return await datasource.getAllEntries();
    }

    return entries;
  }

  /// Refresh points history
  Future<void> refresh() async {
    state = const AsyncValue.loading();
    state = await AsyncValue.guard(() async {
      return await ref
          .read(pointsHistoryLocalDataSourceProvider)
          .getAllEntries();
    });
  }
}

/// Filtered Points History Provider
@riverpod
Future<List<LoyaltyPointEntryModel>> filteredPointsHistory(Ref ref) async {
  final entries = await ref.watch(pointsHistoryProvider.future);
  final filter = ref.watch(pointsHistoryFilterProvider);

  return entries.where((entry) {
    // Filter by start date
    if (filter.startDate != null) {
      final startOfDay = DateTime(
        filter.startDate!.year,
        filter.startDate!.month,
        filter.startDate!.day,
      );
      if (entry.timestamp.isBefore(startOfDay)) {
        return false;
      }
    }

    // Filter by end date
    if (filter.endDate != null) {
      final endOfDay = DateTime(
        filter.endDate!.year,
        filter.endDate!.month,
        filter.endDate!.day,
        23,
        59,
        59,
      );
      if (entry.timestamp.isAfter(endOfDay)) {
        return false;
      }
    }

    return true;
  }).toList();
}
