import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../shared/services/api_service.dart';

/// 学习计划服务
class StudyPlanService {
  final ApiService _apiService;

  StudyPlanService(this._apiService);

  /// 创建学习计划
  Future<Map<String, dynamic>> createStudyPlan({
    required String planName,
    String? description,
    required int dailyGoal,
    String? bookId,
    required String startDate,
    String? endDate,
    String? remindTime,
    String? remindDays,
  }) async {
    final response = await _apiService.post(
      '/study-plans',
      data: {
        'plan_name': planName,
        'description': description,
        'daily_goal': dailyGoal,
        'book_id': bookId,
        'start_date': startDate,
        'end_date': endDate,
        'remind_time': remindTime,
        'remind_days': remindDays,
      },
    );
    return response['data'];
  }

  /// 获取学习计划列表
  Future<List<dynamic>> getUserStudyPlans({String status = 'all'}) async {
    final response = await _apiService.get(
      '/study-plans',
      queryParameters: {'status': status},
    );
    return response['data']['plans'];
  }

  /// 获取今日学习计划
  Future<List<dynamic>> getTodayStudyPlans() async {
    final response = await _apiService.get('/study-plans/today');
    return response['data']['plans'];
  }

  /// 获取学习计划详情
  Future<Map<String, dynamic>> getStudyPlanByID(int planId) async {
    final response = await _apiService.get('/study-plans/$planId');
    return response['data'];
  }

  /// 更新学习计划
  Future<Map<String, dynamic>> updateStudyPlan(
    int planId,
    Map<String, dynamic> updates,
  ) async {
    final response = await _apiService.put('/study-plans/$planId', data: updates);
    return response['data'];
  }

  /// 删除学习计划
  Future<void> deleteStudyPlan(int planId) async {
    await _apiService.delete('/study-plans/$planId');
  }

  /// 更新计划状态
  Future<void> updatePlanStatus(int planId, String status) async {
    await _apiService.patch(
      '/study-plans/$planId/status',
      data: {'status': status},
    );
  }

  /// 记录学习进度
  Future<void> recordStudyProgress(
    int planId, {
    required int wordsStudied,
    int studyDuration = 0,
  }) async {
    await _apiService.post(
      '/study-plans/$planId/progress',
      data: {
        'words_studied': wordsStudied,
        'study_duration': studyDuration,
      },
    );
  }

  /// 获取计划统计
  Future<Map<String, dynamic>> getStudyPlanStatistics(int planId) async {
    final response = await _apiService.get('/study-plans/$planId/statistics');
    return response['data'];
  }
}

/// 学习计划服务提供者
final studyPlanServiceProvider = Provider<StudyPlanService>((ref) {
  final apiService = ref.watch(apiServiceProvider);
  return StudyPlanService(apiService);
});
