placeholders removidos e todos os dados reais colocados, com conquistas e tudo

This commit is contained in:
2026-05-17 17:29:47 +01:00
parent 6ba5c837ce
commit 49a7a6fe02
17 changed files with 4688 additions and 142 deletions

View File

@@ -0,0 +1,343 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:go_router/go_router.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/theme/app_theme_extension.dart';
import '../../../../core/services/auth_service.dart';
import '../../../../core/services/gamification_service.dart';
import '../../../../core/models/class_stats.dart';
import '../../../../core/models/achievement.dart';
import '../widgets/class_analytics_card.dart';
import '../widgets/class_ranking_widget.dart';
import '../widgets/create_achievement_dialog.dart';
/// Analytics page for teachers with class breakdowns and rankings
class AnalyticsPage extends StatefulWidget {
const AnalyticsPage({super.key});
@override
State<AnalyticsPage> createState() => _AnalyticsPageState();
}
class _AnalyticsPageState extends State<AnalyticsPage>
with SingleTickerProviderStateMixin {
late TabController _tabController;
List<ClassStats> _classStats = [];
bool _loading = true;
String? _selectedClassId;
@override
void initState() {
super.initState();
_tabController = TabController(length: 2, vsync: this);
_loadClassStats();
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
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;
final stats = await GamificationService.getClassStats(classId);
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;
});
}
}
}
@override
Widget build(BuildContext context) {
final themeExtras = AppThemeExtras.of(context);
final cs = Theme.of(context).colorScheme;
return Scaffold(
backgroundColor: cs.surface,
body: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: themeExtras.dashboardBackgroundGradient,
stops: themeExtras.dashboardGradientStops,
),
),
child: SafeArea(
child: Column(
children: [
// Header
Container(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Row(
children: [
IconButton(
icon: const Icon(Icons.arrow_back, color: Colors.white),
onPressed: () => context.go('/teacher-dashboard'),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Analytics',
style: TextStyle(
color: Colors.white,
fontSize: 28,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'Acompanhe o desempenho das turmas',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 16,
),
),
],
),
),
IconButton(
icon: const Icon(Icons.add, color: Colors.white),
onPressed: _showCreateAchievementDialog,
tooltip: 'Criar Conquista',
),
],
),
const SizedBox(height: 20),
TabBar(
controller: _tabController,
labelColor: Colors.white,
unselectedLabelColor: Colors.white.withValues(alpha: 0.7),
indicatorColor: Colors.white,
indicatorWeight: 2,
tabs: const [
Tab(text: 'Turmas'),
Tab(text: 'Rankings'),
],
),
],
),
),
// Content
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_buildClassesTab(),
_buildRankingsTab(),
],
),
),
],
),
),
),
);
}
Widget _buildClassesTab() {
if (_loading) {
return const Center(child: CircularProgressIndicator(color: Colors.white));
}
if (_classStats.isEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.analytics_outlined,
size: 64,
color: Colors.white.withValues(alpha: 0.5),
),
const SizedBox(height: 16),
Text(
'Nenhuma turma encontrada',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
'Crie turmas para ver as analytics aqui',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
),
],
),
);
}
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Overview Cards
Row(
children: [
Expanded(
child: _buildOverviewCard(
'Total de Alunos',
'${_classStats.fold(0, (sum, stats) => sum + stats.totalStudents)}',
Icons.people,
Colors.blue,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildOverviewCard(
'Alunos Ativos',
'${_classStats.fold(0, (sum, stats) => sum + stats.activeStudents)}',
Icons.trending_up,
Colors.green,
),
),
],
),
const SizedBox(height: 20),
// Class Cards
..._classStats.map((stats) => Padding(
padding: const EdgeInsets.only(bottom: 16),
child: ClassAnalyticsCard(
classStats: stats,
onTap: () => _showClassRanking(stats),
),
)),
],
),
);
}
Widget _buildRankingsTab() {
if (_selectedClassId == null) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.leaderboard,
size: 64,
color: Colors.white.withValues(alpha: 0.5),
),
const SizedBox(height: 16),
Text(
'Selecione uma turma',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
'Clique em uma turma na aba "Turmas" para ver o ranking',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
),
],
),
);
}
return ClassRankingWidget(classId: _selectedClassId!);
}
Widget _buildOverviewCard(String title, String value, IconData icon, Color color) {
return Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
),
child: Column(
children: [
Icon(icon, color: color, size: 32),
const SizedBox(height: 12),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
title,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 14,
),
textAlign: TextAlign.center,
),
],
),
).animate().scale(duration: 600.ms, curve: Curves.elasticOut);
}
void _showClassRanking(ClassStats stats) {
setState(() {
_selectedClassId = stats.classId;
});
_tabController.animateTo(1); // Mudar para aba de rankings
}
void _showCreateAchievementDialog() {
showDialog(
context: context,
builder: (context) => CreateAchievementDialog(
onAchievementCreated: (achievement) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Conquista "${achievement.name}" criada com sucesso!'),
backgroundColor: Colors.green,
),
);
},
),
);
}
}

View File

@@ -0,0 +1,317 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import '../../../../core/models/class_stats.dart';
import '../../../../core/theme/app_theme_extension.dart';
/// Card displaying analytics for a specific class
class ClassAnalyticsCard extends StatelessWidget {
final ClassStats classStats;
final VoidCallback onTap;
const ClassAnalyticsCard({
super.key,
required this.classStats,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Container(
margin: const EdgeInsets.only(bottom: 16),
child: Material(
color: Colors.transparent,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(20),
child: Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [
cs.primary.withValues(alpha: 0.9),
cs.primary.withValues(alpha: 0.7),
],
),
borderRadius: BorderRadius.circular(20),
boxShadow: [
BoxShadow(
color: cs.shadow.withValues(alpha: 0.1),
blurRadius: 20,
offset: const Offset(0, 10),
),
],
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Header
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
classStats.className,
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'${classStats.activeStudents} de ${classStats.totalStudents} alunos ativos',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 14,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.trending_up, color: Colors.white, size: 16),
const SizedBox(width: 4),
Text(
'${(classStats.averageProgress * 100).toInt()}%',
style: const TextStyle(
color: Colors.white,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
const SizedBox(height: 20),
// Progress Bar
Container(
height: 8,
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.3),
borderRadius: BorderRadius.circular(4),
),
child: FractionallySizedBox(
alignment: Alignment.centerLeft,
widthFactor: classStats.averageProgress.clamp(0.0, 1.0),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
AppThemeExtras.of(context).heroProgressStart,
AppThemeExtras.of(context).heroProgressEnd,
],
),
borderRadius: BorderRadius.circular(4),
),
),
),
),
const SizedBox(height: 20),
// Stats Grid
Row(
children: [
Expanded(
child: _buildStatCard(
icon: Icons.quiz,
value: '${classStats.activeQuizzes}',
label: 'Quizzes Ativos',
context: context,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
icon: Icons.description,
value: '${classStats.totalContent}',
label: 'Conteúdos',
context: context,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildStatCard(
icon: Icons.warning,
value: '${classStats.studentsNeedingSupport.length}',
label: 'Precisam Apoio',
context: context,
isWarning: classStats.studentsNeedingSupport.isNotEmpty,
),
),
],
),
// Students needing support preview
if (classStats.studentsNeedingSupport.isNotEmpty) ...[
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.priority_high,
color: Colors.orange.withValues(alpha: 0.8),
size: 16,
),
const SizedBox(width: 6),
Text(
'Alunos que precisam de atenção:',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.9),
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
const SizedBox(height: 8),
...classStats.studentsNeedingSupport.take(3).map((student) => Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Row(
children: [
Container(
width: 6,
height: 6,
decoration: const BoxDecoration(
color: Colors.orange,
shape: BoxShape.circle,
),
),
const SizedBox(width: 8),
Expanded(
child: Text(
student.studentName,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 11,
),
),
),
Text(
'${student.averageScore.toInt()}%',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 11,
fontWeight: FontWeight.bold,
),
),
],
),
)),
if (classStats.studentsNeedingSupport.length > 3)
Text(
'+${classStats.studentsNeedingSupport.length - 3} alunos',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.6),
fontSize: 10,
),
),
],
),
),
],
// Click indicator
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Ver ranking detalhado',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 12,
),
),
const SizedBox(width: 4),
Icon(
Icons.arrow_forward,
color: Colors.white.withValues(alpha: 0.8),
size: 12,
),
],
),
],
),
),
),
),
).animate().scale(duration: 600.ms, curve: Curves.elasticOut);
}
Widget _buildStatCard({
required IconData icon,
required String value,
required String label,
required BuildContext context,
bool isWarning = false,
}) {
final cs = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.15),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: Colors.white.withValues(alpha: 0.3),
width: 1,
),
),
child: Column(
children: [
Icon(
icon,
color: isWarning ? Colors.orange : Colors.white,
size: 20,
),
const SizedBox(height: 6),
Text(
value,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
label,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 10,
),
textAlign: TextAlign.center,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
);
}
}

View File

@@ -0,0 +1,432 @@
import 'package:flutter/material.dart';
import 'package:flutter_animate/flutter_animate.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '../../../../core/services/gamification_service.dart';
import '../../../../core/models/class_stats.dart';
import '../../../../core/theme/app_theme_extension.dart';
/// Widget displaying student ranking for a specific class
class ClassRankingWidget extends StatefulWidget {
final String classId;
const ClassRankingWidget({
super.key,
required this.classId,
});
@override
State<ClassRankingWidget> createState() => _ClassRankingWidgetState();
}
class _ClassRankingWidgetState extends State<ClassRankingWidget> {
List<StudentRanking> _rankings = [];
ClassStats? _classStats;
bool _loading = true;
String _searchQuery = '';
@override
void initState() {
super.initState();
_loadRankingData();
}
Future<void> _loadRankingData() async {
try {
final results = await Future.wait([
GamificationService.getClassRanking(widget.classId),
GamificationService.getClassStats(widget.classId),
]);
final rankings = results[0] as List<StudentRanking>;
final classStats = results[1] as ClassStats?;
if (mounted) {
setState(() {
_rankings = rankings;
_classStats = classStats;
_loading = false;
});
}
} catch (e) {
print('Error loading ranking data: $e');
if (mounted) {
setState(() {
_loading = false;
});
}
}
}
List<StudentRanking> get _filteredRankings {
if (_searchQuery.isEmpty) return _rankings;
return _rankings.where((student) =>
student.studentName.toLowerCase().contains(_searchQuery.toLowerCase()) ||
student.studentEmail.toLowerCase().contains(_searchQuery.toLowerCase())
).toList();
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
if (_loading) {
return const Center(
child: CircularProgressIndicator(color: Colors.white),
);
}
return Container(
margin: const EdgeInsets.all(24),
child: Column(
children: [
// Header with class info
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [cs.primary, cs.primary.withValues(alpha: 0.8)],
),
borderRadius: BorderRadius.circular(16),
),
child: Column(
children: [
Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_classStats?.className ?? 'Carregando...',
style: const TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
'${_rankings.length} alunos • Progresso médio: ${((_classStats?.averageProgress ?? 0) * 100).toInt()}%',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.8),
fontSize: 14,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(16),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.leaderboard, color: Colors.white, size: 16),
const SizedBox(width: 4),
Text(
'Ranking',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
],
),
),
],
),
],
),
),
const SizedBox(height: 20),
// Search bar
Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
),
child: Row(
children: [
Icon(Icons.search, color: Colors.white.withValues(alpha: 0.7)),
const SizedBox(width: 12),
Expanded(
child: TextField(
onChanged: (value) {
setState(() {
_searchQuery = value;
});
},
style: const TextStyle(color: Colors.white),
decoration: InputDecoration(
hintText: 'Buscar aluno...',
hintStyle: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
),
border: InputBorder.none,
),
),
),
if (_searchQuery.isNotEmpty)
IconButton(
icon: Icon(Icons.clear, color: Colors.white.withValues(alpha: 0.7)),
onPressed: () {
setState(() {
_searchQuery = '';
});
},
),
],
),
),
const SizedBox(height: 20),
// Ranking list
Expanded(
child: _filteredRankings.isEmpty
? _buildEmptyState()
: ListView.builder(
padding: EdgeInsets.zero,
itemCount: _filteredRankings.length,
itemBuilder: (context, index) {
final student = _filteredRankings[index];
final rankPosition = _rankings.indexOf(student) + 1;
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: _buildStudentRankingCard(student, rankPosition),
);
},
),
),
],
),
);
}
Widget _buildEmptyState() {
if (_searchQuery.isNotEmpty) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.search_off,
size: 64,
color: Colors.white.withValues(alpha: 0.5),
),
const SizedBox(height: 16),
Text(
'Nenhum aluno encontrado',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
'Tente buscar com outros termos',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
),
],
),
);
}
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(
Icons.people_outline,
size: 64,
color: Colors.white.withValues(alpha: 0.5),
),
const SizedBox(height: 16),
Text(
'Nenhum aluno na turma',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 18,
),
),
const SizedBox(height: 8),
Text(
'Os alunos aparecerão aqui quando se matricularem',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.5),
fontSize: 14,
),
),
],
),
);
}
Widget _buildStudentRankingCard(StudentRanking student, int rankPosition) {
final cs = Theme.of(context).colorScheme;
// Determinar cor baseada na posição
Color rankColor;
IconData rankIcon;
if (rankPosition == 1) {
rankColor = Colors.amber;
rankIcon = Icons.emoji_events;
} else if (rankPosition == 2) {
rankColor = Colors.grey.withValues(alpha: 0.8);
rankIcon = Icons.workspace_premium;
} else if (rankPosition == 3) {
rankColor = Colors.brown.withValues(alpha: 0.8);
rankIcon = Icons.military_tech;
} else {
rankColor = Colors.white.withValues(alpha: 0.7);
rankIcon = Icons.numbers;
}
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: Colors.white.withValues(alpha: 0.2)),
),
child: Row(
children: [
// Rank position
Container(
width: 40,
height: 40,
decoration: BoxDecoration(
color: rankColor.withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(20),
border: Border.all(color: rankColor.withValues(alpha: 0.5)),
),
child: Center(
child: rankPosition <= 3
? Icon(rankIcon, color: rankColor, size: 20)
: Text(
'$rankPosition',
style: TextStyle(
color: rankColor,
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
),
const SizedBox(width: 16),
// Student info
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
student.studentName,
style: const TextStyle(
color: Colors.white,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
student.studentEmail,
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 12,
),
),
],
),
),
// Stats
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
// Overall score
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _getScoreColor(student.overallScore).withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'${student.overallScore.toInt()}%',
style: TextStyle(
color: _getScoreColor(student.overallScore),
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 4),
// Quiz completion
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.quiz,
color: Colors.white.withValues(alpha: 0.7),
size: 12,
),
const SizedBox(width: 4),
Text(
'${student.completedQuizzes}/${student.totalQuizzes}',
style: TextStyle(
color: Colors.white.withValues(alpha: 0.7),
fontSize: 11,
),
),
],
),
const SizedBox(height: 2),
// Streak
if (student.currentStreak > 0)
Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.local_fire_department,
color: Colors.orange.withValues(alpha: 0.8),
size: 12,
),
const SizedBox(width: 4),
Text(
'${student.currentStreak}d',
style: TextStyle(
color: Colors.orange.withValues(alpha: 0.8),
fontSize: 11,
),
),
],
),
],
),
],
),
).animate().slideX(duration: 300.ms, curve: Curves.easeOut);
}
Color _getScoreColor(double score) {
if (score >= 80) return Colors.green;
if (score >= 60) return Colors.blue;
if (score >= 40) return Colors.orange;
return Colors.red;
}
}

View File

@@ -0,0 +1,633 @@
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import '../../../../core/services/gamification_service.dart';
import '../../../../core/models/achievement.dart';
/// Dialog for creating custom achievements
class CreateAchievementDialog extends StatefulWidget {
final Function(Achievement) onAchievementCreated;
const CreateAchievementDialog({
super.key,
required this.onAchievementCreated,
});
@override
State<CreateAchievementDialog> createState() => _CreateAchievementDialogState();
}
class _CreateAchievementDialogState extends State<CreateAchievementDialog> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _descriptionController = TextEditingController();
final _valueController = TextEditingController();
String _selectedCategory = 'quiz';
String _selectedRequirementType = 'quiz_completion';
String _selectedOperator = '>=';
String _selectedIcon = 'star';
String _selectedRarity = 'common';
int _points = 10;
final List<String> _categories = [
'quiz',
'study_time',
'streak',
'concept',
'general',
];
final List<String> _requirementTypes = [
'quiz_completion',
'quiz_score',
'study_time',
'streak_days',
'concepts_mastered',
];
final List<String> _operators = ['>=', '==', '>'];
final List<String> _icons = [
'star',
'emoji_events',
'school',
'local_fire_department',
'schedule',
'trending_up',
'military_tech',
'workspace_premium',
'psychology',
'lightbulb',
];
final List<String> _rarities = [
'common',
'rare',
'epic',
'legendary',
];
final Map<String, int> _rarityPoints = {
'common': 10,
'rare': 25,
'epic': 50,
'legendary': 100,
};
@override
void dispose() {
_nameController.dispose();
_descriptionController.dispose();
_valueController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cs = Theme.of(context).colorScheme;
return Dialog(
backgroundColor: cs.surface,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
child: Container(
width: MediaQuery.of(context).size.width * 0.8,
constraints: BoxConstraints(
maxHeight: MediaQuery.of(context).size.height * 0.75,
minWidth: 280,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// Header
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [cs.primary, cs.primary.withValues(alpha: 0.8)],
),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
child: Row(
children: [
const Icon(Icons.emoji_events, color: Colors.white, size: 28),
const SizedBox(width: 12),
const Expanded(
child: Text(
'Criar Nova Conquista',
style: TextStyle(
color: Colors.white,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.of(context).pop(),
),
],
),
),
// Form
Expanded(
child: Form(
key: _formKey,
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Basic Info
_buildSectionTitle('Informações Básicas'),
const SizedBox(height: 16),
_buildTextField(
controller: _nameController,
label: 'Nome da Conquista',
hint: 'Ex: Mestre dos Quizzes',
validator: (value) {
if (value == null || value.isEmpty) {
return 'Campo obrigatório';
}
return null;
},
),
const SizedBox(height: 16),
_buildTextField(
controller: _descriptionController,
label: 'Descrição',
hint: 'Ex: Complete 10 quizzes com 100% de acerto',
maxLines: 2,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Campo obrigatório';
}
return null;
},
),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDropdownField<String>(
label: 'Categoria',
value: _selectedCategory,
items: _categories,
onChanged: (value) {
setState(() {
_selectedCategory = value!;
});
},
),
),
const SizedBox(width: 16),
Expanded(
child: _buildDropdownField<String>(
label: 'Ícone',
value: _selectedIcon,
items: _icons,
onChanged: (value) {
setState(() {
_selectedIcon = value!;
});
},
),
),
],
),
const SizedBox(height: 16),
// Requirements
_buildSectionTitle('Requisitos'),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDropdownField<String>(
label: 'Tipo de Requisito',
value: _selectedRequirementType,
items: _requirementTypes,
onChanged: (value) {
setState(() {
_selectedRequirementType = value!;
});
},
),
),
const SizedBox(width: 16),
Expanded(
child: _buildDropdownField<String>(
label: 'Operador',
value: _selectedOperator,
items: _operators,
onChanged: (value) {
setState(() {
_selectedOperator = value!;
});
},
),
),
],
),
const SizedBox(height: 16),
_buildTextField(
controller: _valueController,
label: 'Valor',
hint: 'Ex: 10',
keyboardType: TextInputType.number,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Campo obrigatório';
}
if (int.tryParse(value) == null) {
return 'Digite um número válido';
}
return null;
},
),
const SizedBox(height: 16),
// Reward
_buildSectionTitle('Recompensa'),
const SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDropdownField<String>(
label: 'Raridade',
value: _selectedRarity,
items: _rarities,
onChanged: (value) {
setState(() {
_selectedRarity = value!;
_points = _rarityPoints[value]!;
});
},
),
),
const SizedBox(width: 16),
Expanded(
child: Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: cs.primaryContainer,
borderRadius: BorderRadius.circular(12),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Pontos',
style: TextStyle(
color: cs.onPrimaryContainer,
fontSize: 12,
),
),
const SizedBox(height: 4),
Text(
'$_points',
style: TextStyle(
color: cs.onPrimaryContainer,
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
],
),
),
),
],
),
const SizedBox(height: 16),
// Preview
_buildSectionTitle('Preview'),
const SizedBox(height: 16),
_buildAchievementPreview(),
],
),
),
),
),
// Actions
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: cs.surfaceContainerHighest,
borderRadius: const BorderRadius.only(
bottomLeft: Radius.circular(20),
bottomRight: Radius.circular(20),
),
),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () => Navigator.of(context).pop(),
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 12),
side: BorderSide(color: cs.outline),
),
child: Text('Cancelar', style: TextStyle(color: cs.onSurface)),
),
),
const SizedBox(width: 12),
Expanded(
child: ElevatedButton(
onPressed: _createAchievement,
style: ElevatedButton.styleFrom(
backgroundColor: cs.primary,
foregroundColor: cs.onPrimary,
padding: const EdgeInsets.symmetric(vertical: 12),
),
child: const Text('Criar Conquista'),
),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
final cs = Theme.of(context).colorScheme;
return Text(
title,
style: TextStyle(
color: cs.onSurface,
fontSize: 16,
fontWeight: FontWeight.bold,
),
);
}
Widget _buildTextField({
required TextEditingController controller,
required String label,
required String hint,
int maxLines = 1,
TextInputType? keyboardType,
String? Function(String?)? validator,
}) {
final cs = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
color: cs.onSurface,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
TextFormField(
controller: controller,
decoration: InputDecoration(
hintText: hint,
hintStyle: TextStyle(color: cs.onSurfaceVariant),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.outline),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.outline),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.primary, width: 2),
),
contentPadding: const EdgeInsets.all(16),
),
maxLines: maxLines,
keyboardType: keyboardType,
validator: validator,
),
],
);
}
Widget _buildDropdownField<T>({
required String label,
required T value,
required List<T> items,
required Function(T?) onChanged,
}) {
final cs = Theme.of(context).colorScheme;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
color: cs.onSurface,
fontSize: 14,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 8),
DropdownButtonFormField<T>(
isExpanded: true,
value: value,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.outline),
),
enabledBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.outline),
),
focusedBorder: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
borderSide: BorderSide(color: cs.primary, width: 2),
),
contentPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
),
items: items.map((item) {
return DropdownMenuItem(
value: item,
child: Text(
item.toString().split('_').map((word) =>
word[0].toUpperCase() + word.substring(1)
).join(' '),
style: const TextStyle(fontSize: 12),
overflow: TextOverflow.ellipsis,
),
);
}).toList(),
onChanged: onChanged,
),
],
);
}
Widget _buildAchievementPreview() {
final cs = Theme.of(context).colorScheme;
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
cs.primary.withValues(alpha: 0.1),
cs.primary.withValues(alpha: 0.05),
],
),
borderRadius: BorderRadius.circular(16),
border: Border.all(color: cs.primary.withValues(alpha: 0.3)),
),
child: Row(
children: [
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: _getRarityColor().withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(24),
border: Border.all(color: _getRarityColor().withValues(alpha: 0.5)),
),
child: Icon(
_getIconData(),
color: _getRarityColor(),
size: 24,
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_nameController.text.isEmpty ? 'Nome da Conquista' : _nameController.text,
style: TextStyle(
color: cs.onSurface,
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
_descriptionController.text.isEmpty
? 'Descrição da conquista'
: _descriptionController.text,
style: TextStyle(
color: cs.onSurfaceVariant,
fontSize: 12,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _getRarityColor().withValues(alpha: 0.2),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'$_points pts',
style: TextStyle(
color: _getRarityColor(),
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
IconData _getIconData() {
switch (_selectedIcon) {
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 'military_tech': return Icons.military_tech;
case 'workspace_premium': return Icons.workspace_premium;
case 'psychology': return Icons.psychology;
case 'lightbulb': return Icons.lightbulb;
default: return Icons.star;
}
}
Color _getRarityColor() {
switch (_selectedRarity) {
case 'common': return Colors.grey;
case 'rare': return Colors.blue;
case 'epic': return Colors.purple;
case 'legendary': return Colors.orange;
default: return Colors.grey;
}
}
Future<void> _createAchievement() async {
if (!_formKey.currentState!.validate()) return;
try {
final user = FirebaseAuth.instance.currentUser;
if (user == null) return;
final achievement = Achievement(
id: '', // Will be generated by Firestore
name: _nameController.text,
description: _descriptionController.text,
icon: _selectedIcon,
category: _selectedCategory,
requirements: AchievementRequirement(
type: _selectedRequirementType,
value: int.parse(_valueController.text),
operator: _selectedOperator,
),
points: _points,
rarity: _selectedRarity,
isActive: true,
createdAt: DateTime.now(),
createdBy: user.uid,
);
final achievementId = await GamificationService.createCustomAchievement(
teacherId: user.uid,
name: achievement.name,
description: achievement.description,
icon: achievement.icon,
category: achievement.category,
requirements: achievement.requirements,
points: achievement.points,
rarity: achievement.rarity,
);
final createdAchievement = achievement.copyWith(id: achievementId);
widget.onAchievementCreated(createdAchievement);
Navigator.of(context).pop();
} catch (e) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Erro ao criar conquista: $e'),
backgroundColor: Colors.red,
),
);
}
}
}