import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';

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

/// Página de conquistas para alunos
class StudentAchievementsPage extends StatefulWidget {
  const StudentAchievementsPage({super.key});

  @override
  State<StudentAchievementsPage> createState() =>
      _StudentAchievementsPageState();
}

class _StudentAchievementsPageState extends State<StudentAchievementsPage> {
  UserStats? _userStats;
  List<Achievement> _allAchievements = [];
  List<Achievement> _unlockedAchievements = [];
  List<Achievement> _lockedAchievements = [];
  bool _loading = true;

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

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

      final [stats, allAchievements] = await Future.wait([
        GamificationService.getUserStats(user.uid),
        GamificationService.getAvailableAchievements(),
      ]);

      final userStats = stats as UserStats?;
      final achievements = allAchievements as List<Achievement>;

      if (userStats != null) {
        final unlockedIds = userStats.unlockedAchievements
            .map((ua) => ua.achievementId)
            .toSet();

        final unlocked = achievements
            .where((a) => unlockedIds.contains(a.id))
            .toList();

        final locked = achievements
            .where((a) => !unlockedIds.contains(a.id))
            .toList();

        if (mounted) {
          setState(() {
            _userStats = userStats;
            _allAchievements = achievements;
            _unlockedAchievements = unlocked;
            _lockedAchievements = locked;
            _loading = false;
          });
        }
      }
    } catch (e) {
      print('Error loading achievements: $e');
      if (mounted) {
        setState(() {
          _loading = false;
        });
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeExtras = AppThemeExtras.of(context);
    final cs = Theme.of(context).colorScheme;

    return Scaffold(
      backgroundColor: cs.surface,
      appBar: AppBar(
        backgroundColor: cs.primary,
        foregroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => context.go('/student-dashboard'),
        ),
        title: const Text(
          'Minhas Conquistas',
          style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
        ),
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: 16),
            child: Center(
              child: Text(
                '${_unlockedAchievements.length}/${_allAchievements.length}',
                style: TextStyle(
                  color: Colors.white.withValues(alpha: 0.9),
                  fontSize: 14,
                  fontWeight: FontWeight.w500,
                ),
              ),
            ),
          ),
        ],
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [cs.primary.withValues(alpha: 0.05), cs.surface],
          ),
        ),
        child: SafeArea(
          top: false,
          child: Column(
            children: [
              const SizedBox(height: 52),
              // Content
              Expanded(
                child: _loading
                    ? const Center(child: CircularProgressIndicator())
                    : DefaultTabController(
                        length: 2,
                        child: Column(
                          children: [
                            // Tabs
                            Container(
                              margin: const EdgeInsets.all(16),
                              decoration: BoxDecoration(
                                color: cs.surfaceContainerHighest,
                                borderRadius: BorderRadius.circular(12),
                              ),
                              child: TabBar(
                                labelColor: cs.onPrimary,
                                unselectedLabelColor: cs.onSurfaceVariant,
                                indicator: BoxDecoration(
                                  color: cs.primary,
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                indicatorSize: TabBarIndicatorSize.tab,
                                tabs: const [
                                  Tab(
                                    icon: Icon(Icons.emoji_events),
                                    text: 'Desbloqueadas',
                                  ),
                                  Tab(
                                    icon: Icon(Icons.lock_outline),
                                    text: 'Bloqueadas',
                                  ),
                                ],
                              ),
                            ),

                            // Tab Content
                            Expanded(
                              child: TabBarView(
                                children: [
                                  _buildUnlockedAchievements(),
                                  _buildLockedAchievements(),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildUnlockedAchievements() {
    if (_unlockedAchievements.isEmpty) {
      return _buildEmptyState(
        icon: Icons.emoji_events_outlined,
        title: 'Nenhuma conquista desbloqueada',
        subtitle:
            'Complete quizzes e mantenha seu streak para desbloquear conquistas!',
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _unlockedAchievements.length,
      itemBuilder: (context, index) {
        final achievement = _unlockedAchievements[index];
        return _buildAchievementCard(achievement, isUnlocked: true)
            .animate()
            .fadeIn(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut,
            )
            .then(delay: Duration(milliseconds: index * 50));
      },
    );
  }

  Widget _buildLockedAchievements() {
    if (_lockedAchievements.isEmpty) {
      return _buildEmptyState(
        icon: Icons.emoji_events,
        title: 'Parabéns!',
        subtitle: 'Você desbloqueou todas as conquistas disponíveis!',
      );
    }

    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: _lockedAchievements.length,
      itemBuilder: (context, index) {
        final achievement = _lockedAchievements[index];
        return _buildAchievementCard(achievement, isUnlocked: false)
            .animate()
            .fadeIn(
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut,
            )
            .then(delay: Duration(milliseconds: index * 50));
      },
    );
  }

  Widget _buildAchievementCard(
    Achievement achievement, {
    required bool isUnlocked,
  }) {
    final cs = Theme.of(context).colorScheme;
    final color = _getRarityColor(achievement.rarity);

    return Container(
      margin: const EdgeInsets.only(bottom: 12),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: isUnlocked ? cs.surface : cs.surfaceContainerHighest,
        borderRadius: BorderRadius.circular(16),
        border: Border.all(
          color: isUnlocked
              ? color.withValues(alpha: 0.3)
              : cs.outline.withValues(alpha: 0.2),
          width: isUnlocked ? 2 : 1,
        ),
        boxShadow: [
          BoxShadow(
            color: cs.shadow.withValues(alpha: isUnlocked ? 0.1 : 0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Row(
        children: [
          // Icon
          Container(
            width: 48,
            height: 48,
            decoration: BoxDecoration(
              color: isUnlocked
                  ? color.withValues(alpha: 0.2)
                  : cs.outline.withValues(alpha: 0.2),
              borderRadius: BorderRadius.circular(24),
            ),
            child: Icon(
              _getIconData(achievement.icon),
              color: isUnlocked ? color : cs.outline,
              size: 24,
            ),
          ),
          const SizedBox(width: 16),

          // Content
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  achievement.name,
                  style: TextStyle(
                    color: isUnlocked ? cs.onSurface : cs.onSurfaceVariant,
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 4),
                Text(
                  achievement.description,
                  style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    Container(
                      padding: const EdgeInsets.symmetric(
                        horizontal: 8,
                        vertical: 4,
                      ),
                      decoration: BoxDecoration(
                        color: _getRarityColor(
                          achievement.rarity,
                        ).withValues(alpha: 0.2),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Text(
                        achievement.rarity.toUpperCase(),
                        style: TextStyle(
                          color: _getRarityColor(achievement.rarity),
                          fontSize: 10,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      '+${achievement.points} pts',
                      style: TextStyle(
                        color: cs.primary,
                        fontSize: 12,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

          // Status
          if (isUnlocked)
            Icon(Icons.check_circle, color: Colors.green, size: 24)
          else
            Icon(Icons.lock, color: cs.outline, size: 24),
        ],
      ),
    );
  }

  Widget _buildEmptyState({
    required IconData icon,
    required String title,
    required String subtitle,
  }) {
    final cs = Theme.of(context).colorScheme;

    return Center(
      child: Padding(
        padding: const EdgeInsets.all(32),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(icon, size: 64, color: cs.onSurfaceVariant),
            const SizedBox(height: 16),
            Text(
              title,
              style: TextStyle(
                color: cs.onSurface,
                fontSize: 20,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 8),
            Text(
              subtitle,
              style: TextStyle(color: cs.onSurfaceVariant, fontSize: 14),
              textAlign: TextAlign.center,
            ),
          ],
        ),
      ),
    );
  }

  Color _getRarityColor(String rarity) {
    switch (rarity) {
      case 'common':
        return Colors.grey;
      case 'rare':
        return Colors.blue;
      case 'epic':
        return Colors.purple;
      case 'legendary':
        return Colors.orange;
      default:
        return Colors.grey;
    }
  }

  IconData _getIconData(String iconName) {
    switch (iconName) {
      case 'emoji_events':
        return Icons.emoji_events;
      case 'school':
        return Icons.school;
      case 'local_fire_department':
        return Icons.local_fire_department;
      case 'schedule':
        return Icons.schedule;
      case 'trending_up':
        return Icons.trending_up;
      case 'star':
        return Icons.star;
      case 'military_tech':
        return Icons.military_tech;
      case 'workspace_premium':
        return Icons.workspace_premium;
      case 'psychology':
        return Icons.psychology;
      case 'lightbulb':
        return Icons.lightbulb;
      case 'whatshot':
        return Icons.whatshot;
      case 'stars':
        return Icons.stars;
      default:
        return Icons.emoji_events;
    }
  }
}
