import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

import '../../../../core/services/auth_service.dart';
import '../../../../core/services/gamification_service.dart';
import '../../../../core/models/class_stats.dart';

/// Analytics preview section for teacher dashboard
class TeacherAnalyticsPreviewWidget extends StatefulWidget {
  const TeacherAnalyticsPreviewWidget({super.key});

  @override
  State<TeacherAnalyticsPreviewWidget> createState() =>
      _TeacherAnalyticsPreviewWidgetState();
}

class _TeacherAnalyticsPreviewWidgetState
    extends State<TeacherAnalyticsPreviewWidget> {
  List<StudentRanking> _topStudents = [];
  bool _loading = true;

  @override
  void initState() {
    super.initState();
    _loadTopStudents();
  }

  Future<void> _loadTopStudents() async {
    try {
      final user = AuthService.currentUser;
      if (user == null) return;

      // Obter turmas do professor
      final classesSnapshot = await FirebaseFirestore.instance
          .collection('classes')
          .where('teacherId', isEqualTo: user.uid)
          .get();

      List<StudentRanking> allStudents = [];

      // Buscar ranking de cada turma
      for (final classDoc in classesSnapshot.docs) {
        final classId = classDoc.id;
        // Forçar atualização para obter dados mais recentes
        final rankings = await GamificationService.getClassRanking(classId);
        allStudents.addAll(rankings);
      }

      // Ordenar por score e pegar os top 4
      allStudents.sort((a, b) => b.overallScore.compareTo(a.overallScore));
      final top4 = allStudents.take(4).toList();

      if (mounted) {
        setState(() {
          _topStudents = top4;
          _loading = false;
        });
      }
    } catch (e) {
      print('Error loading top students: $e');
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            _buildQuickStat(
              icon: Icons.check_circle,
              label: 'Alunos Ativos',
              value: '18/24',
              color: Theme.of(context).colorScheme.primary,
            ),
            const SizedBox(width: 12),
            _buildQuickStat(
              icon: Icons.warning_amber,
              label: 'Precisam Apoio',
              value: '3',
              color: Theme.of(context).colorScheme.secondary,
            ),
            const SizedBox(width: 12),
            _buildQuickStat(
              icon: Icons.emoji_events,
              label: 'Média Turma',
              value: '72%',
              color: Theme.of(context).colorScheme.primary.withOpacity(0.8),
            ),
          ],
        ),
        const SizedBox(height: 20),

        // Top Performing Students Preview
        Row(
          children: [
            Icon(
              Icons.leaderboard,
              color: Theme.of(context).colorScheme.secondary,
              size: 20,
            ),
            const SizedBox(width: 8),
            Text(
              'Melhores Desempenhos',
              style: TextStyle(
                color: Theme.of(context).colorScheme.onSurface,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),

        // Student List Preview
        if (_loading)
          const Center(child: CircularProgressIndicator())
        else if (_topStudents.isEmpty)
          const Center(
            child: Text(
              'Nenhum aluno encontrado',
              style: TextStyle(fontSize: 14),
            ),
          )
        else
          ..._topStudents.asMap().entries.map((entry) {
            final index = entry.key;
            final student = entry.value;
            final color = _getStudentColor(context, index);

            return Padding(
              padding: const EdgeInsets.only(bottom: 8),
              child: _buildStudentPerformanceItem(
                context,
                student.studentName,
                student.overallScore.toInt(),
                color,
              ),
            );
          }).toList(),

        const SizedBox(height: 20),

        // Content Quality Alert
        Container(
          padding: const EdgeInsets.all(16),
          decoration: BoxDecoration(
            color: Theme.of(context).colorScheme.surfaceContainerHighest,
            borderRadius: BorderRadius.circular(12),
            border: Border.all(
              color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
            ),
          ),
          child: Row(
            children: [
              Icon(
                Icons.info_outline,
                color: Theme.of(context).colorScheme.primary,
                size: 20,
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Qualidade do Conteúdo',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurface,
                        fontSize: 14,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 2),
                    Text(
                      '12 conteúdos verificados • 2 pendentes de revisão',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurfaceVariant,
                        fontSize: 12,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildQuickStat({
    required IconData icon,
    required String label,
    required String value,
    required Color color,
  }) {
    return Expanded(
      child: Container(
        padding: const EdgeInsets.all(12),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: color.withOpacity(0.3), width: 1),
        ),
        child: Column(
          children: [
            Icon(icon, color: color, size: 20),
            const SizedBox(height: 6),
            Text(
              value,
              style: TextStyle(
                color: color,
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 2),
            Text(
              label,
              style: TextStyle(color: color.withOpacity(0.8), fontSize: 10),
              textAlign: TextAlign.center,
              maxLines: 3,
            ),
          ],
        ),
      ),
    );
  }

  Color _getStudentColor(BuildContext context, int index) {
    final colors = [
      Theme.of(context).colorScheme.tertiary,
      Theme.of(context).colorScheme.primary,
      Theme.of(context).colorScheme.primary,
      Theme.of(context).colorScheme.secondary,
    ];
    return colors[index % colors.length];
  }

  Widget _buildStudentPerformanceItem(
    BuildContext context,
    String name,
    int score,
    Color color,
  ) {
    return Row(
      children: [
        Container(
          width: 32,
          height: 32,
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(16),
          ),
          child: Center(
            child: Text(
              name.split(' ').map((n) => n[0]).take(2).join(),
              style: TextStyle(
                color: color,
                fontSize: 12,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Text(
            name,
            style: TextStyle(
              color: Theme.of(context).colorScheme.onSurfaceVariant,
              fontSize: 14,
            ),
          ),
        ),
        Container(
          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
          decoration: BoxDecoration(
            color: color.withOpacity(0.1),
            borderRadius: BorderRadius.circular(8),
          ),
          child: Text(
            '$score%',
            style: TextStyle(
              color: color,
              fontSize: 12,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ],
    );
  }
}
