import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/learning_progress_model.dart';
import '../services/learning_progress_service.dart';

/// 学习进度状态
class LearningProgressState {
  final List<LearningProgress> progressList;
  final bool isLoading;
  final String? error;

  LearningProgressState({
    this.progressList = const [],
    this.isLoading = false,
    this.error,
  });

  LearningProgressState copyWith({
    List<LearningProgress>? progressList,
    bool? isLoading,
    String? error,
  }) {
    return LearningProgressState(
      progressList: progressList ?? this.progressList,
      isLoading: isLoading ?? this.isLoading,
      error: error,
    );
  }
}

/// 学习进度Notifier
class LearningProgressNotifier extends StateNotifier<LearningProgressState> {
  final LearningProgressService _service = LearningProgressService();

  LearningProgressNotifier() : super(LearningProgressState());

  /// 加载学习进度
  Future<void> loadLearningProgress() async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final response = await _service.getUserLearningProgress();
      
      if (response.success && response.data != null) {
        state = state.copyWith(
          progressList: response.data!,
          isLoading: false,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response.message,
        );
      }
    } catch (e) {
      state = state.copyWith(
        isLoading: false,
        error: '加载学习进度失败: $e',
      );
    }
  }

  /// 刷新学习进度（强制重新加载，不使用缓存）
  Future<void> refreshLearningProgress() async {
    state = state.copyWith(isLoading: true, error: null);
    
    try {
      // 强制重新加载，传入不同的时间戳来绕过缓存
      final response = await _service.getUserLearningProgress();
      
      if (response.success && response.data != null) {
        print('=== 刷新学习进度成功 ===');
        print('数据条数: ${response.data!.length}');
        state = state.copyWith(
          progressList: response.data!,
          isLoading: false,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: response.message,
        );
      }
    } catch (e) {
      print('刷新学习进度失败: $e');
      state = state.copyWith(
        isLoading: false,
        error: '刷新学习进度失败: $e',
      );
    }
  }
}

/// 学习进度Provider
final learningProgressProvider = StateNotifierProvider<LearningProgressNotifier, LearningProgressState>(
  (ref) => LearningProgressNotifier(),
);

/// 学习进度列表Provider（便捷访问）
final learningProgressListProvider = Provider<List<LearningProgress>>((ref) {
  return ref.watch(learningProgressProvider).progressList;
});

/// 学习进度加载状态Provider
final learningProgressLoadingProvider = Provider<bool>((ref) {
  return ref.watch(learningProgressProvider).isLoading;
});
