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

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

/// Hero section for teacher dashboard showing class overview
class TeacherHeroWidget extends StatefulWidget {
  final String userName;

  const TeacherHeroWidget({super.key, required this.userName});

  @override
  State<TeacherHeroWidget> createState() => _TeacherHeroWidgetState();
}

class _TeacherHeroWidgetState extends State<TeacherHeroWidget> {
  List<ClassStats> _classStats = [];
  bool _loading = true;

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

  Future<void> _loadClassStats() 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();

      final classStatsList = <ClassStats>[];

      for (final classDoc in classesSnapshot.docs) {
        final classId = classDoc.id;
        // Forçar atualização para obter dados mais recentes
        final stats = await GamificationService.getClassStats(
          classId,
          forceRefresh: true,
        );
        if (stats != null) {
          classStatsList.add(stats);
        }
      }

      if (mounted) {
        setState(() {
          _classStats = classStatsList;
          _loading = false;
        });
      }
    } catch (e) {
      print('Error loading class stats: $e');
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  int get totalStudents =>
      _classStats.fold(0, (sum, stats) => sum + stats.totalStudents);
  int get activeQuizzes =>
      _classStats.fold(0, (sum, stats) => sum + stats.activeQuizzes);
  int get uploadedContent =>
      _classStats.fold(0, (sum, stats) => sum + stats.totalContent);
  double get classAverageProgress {
    if (_classStats.isEmpty) return 0.0;
    final totalProgress = _classStats.fold(
      0.0,
      (sum, stats) => sum + stats.averageProgress,
    );
    final average = totalProgress / _classStats.length;

    print('=== UI PROGRESS DEBUG ===');
    print('Number of classes: ${_classStats.length}');
    for (int i = 0; i < _classStats.length; i++) {
      print(
        'Class ${i + 1}: ${_classStats[i].className} - ${_classStats[i].averageProgress} (${(_classStats[i].averageProgress * 100).toInt()}%)',
      );
    }
    print('Total progress sum: $totalProgress');
    print('Calculated average: $average (${(average * 100).toInt()}%)');
    print('=== END UI PROGRESS DEBUG ===');

    return average;
  }

  Widget build(BuildContext context) {
    if (_loading) {
      return Container(
        margin: const EdgeInsets.only(bottom: 24),
        child: const Center(child: CircularProgressIndicator()),
      );
    }

    return Container(
      margin: const EdgeInsets.only(bottom: 24),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // Header
          Row(
            children: [
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Visão Geral da Turma',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurface,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    const SizedBox(height: 4),
                    Text(
                      'Acompanhe o progresso dos seus alunos',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurfaceVariant,
                        fontSize: 13,
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                padding: const EdgeInsets.symmetric(
                  horizontal: 12,
                  vertical: 6,
                ),
                decoration: BoxDecoration(
                  color: Theme.of(context).colorScheme.secondary,
                  borderRadius: BorderRadius.circular(20),
                ),
                child: Row(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const Icon(Icons.people, color: Colors.white, size: 16),
                    const SizedBox(width: 4),
                    Text(
                      '$totalStudents alunos',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
          const SizedBox(height: 20),

          // Main Class Progress Card
          Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topLeft,
                end: Alignment.bottomRight,
                colors: [
                  Theme.of(context).colorScheme.primary,
                  Theme.of(context).colorScheme.primary.withOpacity(0.8),
                ],
              ),
              borderRadius: BorderRadius.circular(20),
              boxShadow: [
                BoxShadow(
                  color: Theme.of(context).colorScheme.shadow.withOpacity(0.1),
                  blurRadius: 20,
                  offset: const Offset(0, 10),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Overall Progress
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    const Flexible(
                      child: Text(
                        'Progresso Médio da Turma',
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 15,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    Builder(
                      builder: (context) {
                        final displayValue = (classAverageProgress * 100)
                            .toInt();
                        print('=== RENDER DEBUG ===');
                        print('classAverageProgress: $classAverageProgress');
                        print('displayValue: $displayValue%');
                        print('=== END RENDER DEBUG ===');
                        return Text(
                          '$displayValue%',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 24,
                            fontWeight: FontWeight.bold,
                          ),
                        );
                      },
                    ),
                  ],
                ),
                const SizedBox(height: 16),

                // Progress Bar
                GestureDetector(
                  onTap: () => _showProgressExplanation(context),
                  child: Container(
                    height: 12,
                    decoration: BoxDecoration(
                      color: Colors.white.withOpacity(0.3),
                      borderRadius: BorderRadius.circular(6),
                    ),
                    child: FractionallySizedBox(
                      alignment: Alignment.centerLeft,
                      widthFactor: classAverageProgress,
                      child: Container(
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              AppThemeExtras.of(context).heroProgressStart,
                              AppThemeExtras.of(context).heroProgressEnd,
                            ],
                          ),
                          borderRadius: BorderRadius.circular(6),
                        ),
                      ),
                    ),
                  ),
                ),
                const SizedBox(height: 20),

                // Stats Grid
                Row(
                  children: [
                    Expanded(
                      child: _buildStatCard(
                        icon: Icons.quiz,
                        value: '$activeQuizzes',
                        label: 'Quizzes Ativos',
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: _buildStatCard(
                        icon: Icons.upload_file,
                        value: '$uploadedContent',
                        label: 'Conteúdos',
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          const SizedBox(height: 20),

          // Recent Activity
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: Theme.of(context).colorScheme.surface,
              borderRadius: BorderRadius.circular(16),
              border: Border.all(
                color: Theme.of(context).colorScheme.outline.withOpacity(0.2),
              ),
              boxShadow: [
                BoxShadow(
                  color: Theme.of(context).colorScheme.shadow.withOpacity(0.05),
                  blurRadius: 10,
                  offset: const Offset(0, 4),
                ),
              ],
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Icon(
                      Icons.trending_up,
                      color: Theme.of(context).colorScheme.secondary,
                      size: 20,
                    ),
                    const SizedBox(width: 8),
                    Text(
                      'Atividade Recente',
                      style: TextStyle(
                        color: Theme.of(context).colorScheme.onSurface,
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
                const SizedBox(height: 12),
                ..._buildRecentActivities(),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildStatCard({
    required IconData icon,
    required String value,
    required String label,
  }) {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white.withOpacity(0.2),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.white.withOpacity(0.3), width: 1),
      ),
      child: Column(
        children: [
          Icon(icon, color: Colors.white, size: 24),
          const SizedBox(height: 8),
          Text(
            value,
            style: const TextStyle(
              color: Colors.white,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: const TextStyle(color: Colors.white, fontSize: 11),
            textAlign: TextAlign.center,
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  List<Widget> _buildRecentActivities() {
    final activities = <Widget>[];

    if (_classStats.isEmpty) {
      activities.add(
        _buildActivityItem(
          context,
          'Nenhuma atividade recente',
          'Comece criando turmas e conteúdos',
          Theme.of(context).colorScheme.onSurfaceVariant,
        ),
      );
      return activities;
    }

    // Adicionar atividades baseadas nas estatísticas das turmas
    for (final stats in _classStats.take(3)) {
      if (stats.activeQuizzes > 0) {
        activities.add(
          _buildActivityItem(
            context,
            '${stats.activeQuizzes} quizzes ativos em ${stats.className}',
            'Recente',
            Theme.of(context).colorScheme.primary,
          ),
        );
        activities.add(const SizedBox(height: 8));
      }

      if (stats.studentsNeedingSupport.isNotEmpty) {
        activities.add(
          _buildActivityItem(
            context,
            '${stats.studentsNeedingSupport.length} alunos precisam de apoio em ${stats.className}',
            'Ver analytics',
            Theme.of(context).colorScheme.error,
          ),
        );
        activities.add(const SizedBox(height: 8));
      }

      if (stats.totalContent > 0) {
        activities.add(
          _buildActivityItem(
            context,
            '${stats.totalContent} conteúdos disponíveis em ${stats.className}',
            'Atualizado',
            Theme.of(context).colorScheme.secondary,
          ),
        );
        activities.add(const SizedBox(height: 8));
      }
    }

    // Remover o último SizedBox se existir
    if (activities.isNotEmpty && activities.last is SizedBox) {
      activities.removeLast();
    }

    return activities.isEmpty
        ? [
            _buildActivityItem(
              context,
              'Nenhuma atividade recente',
              'Comece criando turmas e conteúdos',
              Theme.of(context).colorScheme.onSurfaceVariant,
            ),
          ]
        : activities;
  }

  Widget _buildActivityItem(
    BuildContext context,
    String text,
    String time,
    Color color,
  ) {
    return Row(
      children: [
        Container(
          width: 8,
          height: 8,
          decoration: BoxDecoration(color: color, shape: BoxShape.circle),
        ),
        const SizedBox(width: 12),
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                text,
                style: TextStyle(
                  color: Theme.of(context).colorScheme.onSurfaceVariant,
                  fontSize: 14,
                ),
              ),
              const SizedBox(height: 2),
              Text(
                time,
                style: TextStyle(
                  color: Theme.of(
                    context,
                  ).colorScheme.onSurfaceVariant.withValues(alpha: 0.7),
                  fontSize: 12,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  void _showProgressExplanation(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Progresso Médio da Turma'),
        content: const Text(
          'O progresso médio da turma é calculado com base no domínio dos conceitos por cada aluno. '
          'Cada aluno tem um nível de domínio para cada conceito (0-100%), e o progresso médio '
          'é a média de todos esses níveis de domínio em toda a turma.',
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('Entendi'),
          ),
        ],
      ),
    );
  }
}
