import 'package:hive_flutter/hive_flutter.dart';
import 'package:lunchpick/domain/entities/recommendation_record.dart';
import 'package:lunchpick/domain/repositories/recommendation_repository.dart';

class RecommendationRepositoryImpl implements RecommendationRepository {
  static const String _boxName = 'recommendations';

  Future<Box<RecommendationRecord>> get _box async =>
      await Hive.openBox<RecommendationRecord>(_boxName);

  @override
  Future<List<RecommendationRecord>> getAllRecommendationRecords() async {
    final box = await _box;
    final records = box.values.toList();
    records.sort(
      (a, b) => b.recommendationDate.compareTo(a.recommendationDate),
    );
    return records;
  }

  @override
  Future<List<RecommendationRecord>> getRecommendationsByRestaurantId(
    String restaurantId,
  ) async {
    final records = await getAllRecommendationRecords();
    return records.where((r) => r.restaurantId == restaurantId).toList();
  }

  @override
  Future<List<RecommendationRecord>> getRecommendationsByDate(
    DateTime date,
  ) async {
    final records = await getAllRecommendationRecords();
    return records.where((record) {
      return record.recommendationDate.year == date.year &&
          record.recommendationDate.month == date.month &&
          record.recommendationDate.day == date.day;
    }).toList();
  }

  @override
  Future<List<RecommendationRecord>> getRecommendationsByDateRange({
    required DateTime startDate,
    required DateTime endDate,
  }) async {
    final records = await getAllRecommendationRecords();
    return records.where((record) {
      return record.recommendationDate.isAfter(
            startDate.subtract(const Duration(days: 1)),
          ) &&
          record.recommendationDate.isBefore(
            endDate.add(const Duration(days: 1)),
          );
    }).toList();
  }

  @override
  Future<void> addRecommendationRecord(RecommendationRecord record) async {
    final box = await _box;
    await box.put(record.id, record);
  }

  @override
  Future<void> updateRecommendationRecord(RecommendationRecord record) async {
    final box = await _box;
    await box.put(record.id, record);
  }

  @override
  Future<void> deleteRecommendationRecord(String id) async {
    final box = await _box;
    await box.delete(id);
  }

  @override
  Future<void> markAsVisited(String recommendationId) async {
    final box = await _box;
    final record = box.get(recommendationId);
    if (record != null) {
      final updatedRecord = RecommendationRecord(
        id: record.id,
        restaurantId: record.restaurantId,
        recommendationDate: record.recommendationDate,
        visited: true,
        createdAt: record.createdAt,
      );
      await updateRecommendationRecord(updatedRecord);
    }
  }

  @override
  Future<int> getTodayRecommendationCount() async {
    final today = DateTime.now();
    final todayRecords = await getRecommendationsByDate(today);
    return todayRecords.length;
  }

  @override
  Stream<List<RecommendationRecord>> watchRecommendationRecords() async* {
    final box = await _box;
    try {
      yield await getAllRecommendationRecords();
    } catch (_) {
      yield <RecommendationRecord>[];
    }
    yield* box.watch().asyncMap(
      (_) async => await getAllRecommendationRecords(),
    );
  }

  @override
  Future<Map<String, int>> getMonthlyRecommendationStats(
    int year,
    int month,
  ) async {
    final startDate = DateTime(year, month, 1);
    final endDate = DateTime(year, month + 1, 0); // 해당 월의 마지막 날

    final records = await getRecommendationsByDateRange(
      startDate: startDate,
      endDate: endDate,
    );

    final stats = <String, int>{};
    for (final record in records) {
      final dayKey = record.recommendationDate.day.toString();
      stats[dayKey] = (stats[dayKey] ?? 0) + 1;
    }

    return stats;
  }
}
