import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../../../../core/services/auth_service.dart';
import '../../../../core/theme/app_theme_extension.dart';
import '../../../../core/routing/app_router.dart';
import '../widgets/progress_hero_widget.dart';
import '../widgets/quick_access_widget.dart';
import '../widgets/student_classes_list_widget.dart';
import '../widgets/profile_section_widget.dart';

class StudentDashboardPage extends StatefulWidget {
  const StudentDashboardPage({super.key});

  @override
  State<StudentDashboardPage> createState() => _StudentDashboardPageState();
}

class _StudentDashboardPageState extends State<StudentDashboardPage> {
  String _userName = 'Estudante';

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

  Future<void> _checkRoleAndLoadData() async {
    final user = AuthService.currentUser;
    if (user == null) {
      if (mounted) context.go('/role-selection');
      return;
    }
    final role = await AuthService.getUserRole(user.uid);
    if (role != 'student') {
      if (mounted) {
        context.go('/role-selection');
      }
      return;
    }
    await _loadUserData();
  }

  Future<void> _loadUserData() async {
    try {
      final user = AuthService.currentUser;
      if (user != null) {
        print('DEBUG: Loading user data for dashboard');
        print('DEBUG: User email: ${user.email}');
        print('DEBUG: User displayName before reload: ${user.displayName}');

        // Reload user data to get latest information from Firebase
        await user.reload();

        // Get the updated user
        final updatedUser = AuthService.currentUser;
        if (updatedUser != null) {
          print(
            'DEBUG: User displayName after reload: ${updatedUser.displayName}',
          );

          // Use displayName if available, otherwise use email part before @
          String displayName = updatedUser.displayName ?? '';
          print('DEBUG: Initial displayName value: "$displayName"');

          if (displayName.isEmpty && updatedUser.email != null) {
            // Extract name from email (e.g., "fabioceia0223@gmail.com" -> "fabioceia0223")
            displayName = updatedUser.email!.split('@')[0];
            print('DEBUG: Extracted name from email: "$displayName"');
          }
          if (displayName.isEmpty) {
            displayName = 'Estudante';
            print('DEBUG: Using fallback "Estudante"');
          }

          print('DEBUG: Final displayName to use: "$displayName"');
          setState(() {
            _userName = displayName;
          });
        }
      }
    } catch (e) {
      print('DEBUG: Error loading user data: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    final themeExtras = AppThemeExtras.of(context);
    final headerColor = themeExtras.dashboardHeaderTextColor;

    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: themeExtras.dashboardBackgroundGradient,
            stops: themeExtras.dashboardGradientStops,
          ),
        ),
        child: SafeArea(
          child: SingleChildScrollView(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // Header with logout and settings
                  Row(
                    children: [
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              'Bem-vindo, $_userName!',
                              style: TextStyle(
                                color: headerColor,
                                fontSize: 28,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                            const SizedBox(height: 4),
                            Text(
                              'Seu progresso de estudos',
                              style: TextStyle(
                                color: headerColor,
                                fontSize: 16,
                                fontWeight: FontWeight.w300,
                              ),
                            ),
                          ],
                        ),
                      ),
                      IconButton(
                        icon: Icon(Icons.settings, color: headerColor),
                        onPressed: () {
                          AppRouter.goToSettings(context);
                        },
                        tooltip: 'Configurações',
                      ),
                      IconButton(
                        icon: Icon(Icons.logout, color: headerColor),
                        onPressed: () async {
                          await AuthService.signOut();
                          if (mounted) {
                            context.go('/login');
                          }
                        },
                        tooltip: 'Sair',
                      ),
                    ],
                  ),
                  const SizedBox(height: 32),

                  // Progress Hero Section (Priority 1)
                  ProgressHeroWidget(userName: _userName),

                  const SizedBox(height: 24),

                  // Quick Access Section (Priority 2)
                  const QuickAccessWidget(),

                  const SizedBox(height: 24),

                  // Classes List Section (Priority 3)
                  const StudentClassesListWidget(),

                  const SizedBox(height: 24),

                  // Profile Section (Priority 4)
                  const ProfileSectionWidget(),

                  const SizedBox(height: 40),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
