import 'package:cloud_firestore/cloud_firestore.dart';

/// Model para estatísticas da turma (professor)
class ClassStats {
  final String classId;
  final String teacherId;
  final String className;
  final int totalStudents;
  final int activeStudents;
  final double averageProgress;
  final int totalQuizzes;
  final int activeQuizzes;
  final int totalContent;
  final List<WeeklyStats> weeklyStats;
  final List<StudentNeedingSupport> studentsNeedingSupport;
  final DateTime? lastUpdated;

  const ClassStats({
    required this.classId,
    required this.teacherId,
    required this.className,
    required this.totalStudents,
    required this.activeStudents,
    required this.averageProgress,
    required this.totalQuizzes,
    required this.activeQuizzes,
    required this.totalContent,
    required this.weeklyStats,
    required this.studentsNeedingSupport,
    this.lastUpdated,
  });

  factory ClassStats.fromFirestore(Map<String, dynamic> data, String classId) {
    return ClassStats(
      classId: classId,
      teacherId: data['teacherId'] ?? '',
      className: data['className'] ?? '',
      totalStudents: data['totalStudents'] ?? 0,
      activeStudents: data['activeStudents'] ?? 0,
      averageProgress: (data['averageProgress'] ?? 0).toDouble(),
      totalQuizzes: data['totalQuizzes'] ?? 0,
      activeQuizzes: data['activeQuizzes'] ?? 0,
      totalContent: data['totalContent'] ?? 0,
      weeklyStats: (data['weeklyStats'] as List<dynamic>?)
              ?.map((w) => WeeklyStats.fromFirestore(w))
              .toList() ??
          [],
      studentsNeedingSupport: (data['studentsNeedingSupport'] as List<dynamic>?)
              ?.map((s) => StudentNeedingSupport.fromFirestore(s))
              .toList() ??
          [],
      lastUpdated: (data['lastUpdated'] as Timestamp?)?.toDate(),
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      'teacherId': teacherId,
      'className': className,
      'totalStudents': totalStudents,
      'activeStudents': activeStudents,
      'averageProgress': averageProgress,
      'totalQuizzes': totalQuizzes,
      'activeQuizzes': activeQuizzes,
      'totalContent': totalContent,
      'weeklyStats': weeklyStats.map((w) => w.toFirestore()).toList(),
      'studentsNeedingSupport': studentsNeedingSupport.map((s) => s.toFirestore()).toList(),
      'lastUpdated': lastUpdated != null ? Timestamp.fromDate(lastUpdated!) : null,
    };
  }
}

/// Estatísticas semanais da turma
class WeeklyStats {
  final DateTime weekStart;
  final int activeStudents;
  final double averageScore;
  final int totalStudyTime;

  const WeeklyStats({
    required this.weekStart,
    required this.activeStudents,
    required this.averageScore,
    required this.totalStudyTime,
  });

  factory WeeklyStats.fromFirestore(Map<String, dynamic> data) {
    return WeeklyStats(
      weekStart: (data['weekStart'] as Timestamp?)?.toDate() ?? DateTime.now(),
      activeStudents: data['activeStudents'] ?? 0,
      averageScore: (data['averageScore'] ?? 0).toDouble(),
      totalStudyTime: data['totalStudyTime'] ?? 0,
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      'weekStart': Timestamp.fromDate(weekStart),
      'activeStudents': activeStudents,
      'averageScore': averageScore,
      'totalStudyTime': totalStudyTime,
    };
  }
}

/// Aluno que precisa de apoio
class StudentNeedingSupport {
  final String studentId;
  final String studentName;
  final String reason; // 'low_scores', 'inactivity', 'struggling_concept'
  final DateTime lastActivity;
  final double averageScore;

  const StudentNeedingSupport({
    required this.studentId,
    required this.studentName,
    required this.reason,
    required this.lastActivity,
    required this.averageScore,
  });

  factory StudentNeedingSupport.fromFirestore(Map<String, dynamic> data) {
    return StudentNeedingSupport(
      studentId: data['studentId'] ?? '',
      studentName: data['studentName'] ?? '',
      reason: data['reason'] ?? '',
      lastActivity: (data['lastActivity'] as Timestamp?)?.toDate() ?? DateTime.now(),
      averageScore: (data['averageScore'] ?? 0).toDouble(),
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      'studentId': studentId,
      'studentName': studentName,
      'reason': reason,
      'lastActivity': Timestamp.fromDate(lastActivity),
      'averageScore': averageScore,
    };
  }
}

/// Ranking de alunos em uma turma
class StudentRanking {
  final String studentId;
  final String studentName;
  final String studentEmail;
  final double overallScore;
  final int completedQuizzes;
  final int totalQuizzes;
  final double quizCompletionRate;
  final int studyTimeMinutes;
  final int currentStreak;
  final DateTime lastActivity;

  const StudentRanking({
    required this.studentId,
    required this.studentName,
    required this.studentEmail,
    required this.overallScore,
    required this.completedQuizzes,
    required this.totalQuizzes,
    required this.quizCompletionRate,
    required this.studyTimeMinutes,
    required this.currentStreak,
    required this.lastActivity,
  });

  double get quizCompletionPercentage => quizCompletionRate * 100;

  factory StudentRanking.fromFirestore(Map<String, dynamic> data, String studentId) {
    return StudentRanking(
      studentId: studentId,
      studentName: data['studentName'] ?? '',
      studentEmail: data['studentEmail'] ?? '',
      overallScore: (data['overallScore'] ?? 0).toDouble(),
      completedQuizzes: data['completedQuizzes'] ?? 0,
      totalQuizzes: data['totalQuizzes'] ?? 0,
      quizCompletionRate: (data['quizCompletionRate'] ?? 0).toDouble(),
      studyTimeMinutes: data['studyTimeMinutes'] ?? 0,
      currentStreak: data['currentStreak'] ?? 0,
      lastActivity: (data['lastActivity'] as Timestamp?)?.toDate() ?? DateTime.now(),
    );
  }

  Map<String, dynamic> toFirestore() {
    return {
      'studentName': studentName,
      'studentEmail': studentEmail,
      'overallScore': overallScore,
      'completedQuizzes': completedQuizzes,
      'totalQuizzes': totalQuizzes,
      'quizCompletionRate': quizCompletionRate,
      'studyTimeMinutes': studyTimeMinutes,
      'currentStreak': currentStreak,
      'lastActivity': Timestamp.fromDate(lastActivity),
    };
  }
}
