import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:hive_flutter/hive_flutter.dart';
import '../models/teaching_plan.dart';

final teachingPlansProvider =
    StateNotifierProvider<TeachingPlansNotifier, List<TeachingPlan>>((ref) {
  return TeachingPlansNotifier();
});

class TeachingPlansNotifier extends StateNotifier<List<TeachingPlan>> {
  TeachingPlansNotifier() : super([]) {
    _loadPlans();
  }

  void _loadPlans() {
    if (Hive.isBoxOpen('teaching_plans_v2')) {
      final box = Hive.box<TeachingPlan>('teaching_plans_v2');
      state = box.values.toList()..sort((a, b) => b.date.compareTo(a.date));
    }
  }

  Future<void> addPlan(TeachingPlan plan) async {
    final box = Hive.box<TeachingPlan>('teaching_plans_v2');
    await box.put(plan.id, plan);
    _loadPlans();
  }

  Future<void> updatePlan(TeachingPlan plan) async {
    final box = Hive.box<TeachingPlan>('teaching_plans_v2');
    await box.put(plan.id, plan);
    _loadPlans();
  }

  Future<void> deletePlan(String id) async {
    final box = Hive.box<TeachingPlan>('teaching_plans_v2');
    await box.delete(id);
    _loadPlans();
  }
}
