import 'package:english_learning/core/services/repositories/level_repository.dart';
import 'package:english_learning/features/learning/modules/level/models/level_model.dart';
import 'package:flutter/foundation.dart';

class LevelProvider with ChangeNotifier {
  final LevelRepository _levelRepository = LevelRepository();
  List<Level> _levels = [];
  Map<String, dynamic>? _lastCompletedLevel;
  List<String> _unlockedLevels = [];
  bool _isLoading = false;
  String? _error;
  Map<String, dynamic>? _studentAnswers;

  List<Level> get levels => _levels;
  Map<String, dynamic>? get lastCompletedLevel => _lastCompletedLevel;
  List<String> get unlockedLevels => _unlockedLevels;
  bool get isLoading => _isLoading;
  String? get error => _error;
  Map<String, dynamic>? get studentAnswers => _studentAnswers;

  Future<void> fetchLevels(String topicId, String token) async {
    _isLoading = true;
    _error = null;
    notifyListeners();

    try {
      final result = await _levelRepository.getLevels(topicId, token);
      _levels = result['levels'];
      _lastCompletedLevel = result['lastCompletedLevel'];
      _unlockedLevels =
          List<String>.from(_lastCompletedLevel?['UNLOCKED_LEVELS'] ?? []);

      if (_levels.isEmpty) {
        _error = 'No levels found for this topic';
      }
    } catch (e) {
      _error = 'Error fetching levels: ${e.toString()}';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  Level getPretest() {
    return _levels.firstWhere((level) => level.isPretest == 1,
        orElse: () => throw Exception('Pretest not found'));
  }

  bool isPretestFinished(String levelId) {
    return _levels.any(
        (level) => level.idLevel == levelId && level.idStudentLearning != null);
  }

  int getPretestScore(String levelId) {
    final pretest = _levels.firstWhere(
        (level) => level.idLevel == levelId && level.isPretest == 1,
        orElse: () => throw Exception('Null'));
    return pretest.score ?? 0;
  }

  int getLevelScore(String levelId) {
    final level = _levels.firstWhere((level) => level.idLevel == levelId,
        orElse: () => throw Exception('Null'));
    return level.score ?? 0;
  }

  bool isLevelAllowed(String levelId) {
    return _unlockedLevels.contains(
        _levels.firstWhere((level) => level.idLevel == levelId).nameLevel);
  }

  bool isLevelCompleted(String levelId) {
    return _levels.any(
        (level) => level.idLevel == levelId && level.idStudentLearning != null);
  }
}
