package com.example.los_chatos

import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.los_chatos.network.*
import com.example.los_chatos.screens.ReportsScreen
import com.example.los_chatos.ui.theme.Los_chatosTheme
import kotlinx.coroutines.launch
import java.net.URLDecoder
import java.net.URLEncoder
import java.nio.charset.StandardCharsets

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContent {
            Los_chatosTheme {
                Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
                    AppNavigation(modifier = Modifier.padding(innerPadding))
                }
            }
        }
    }
}

@Composable
fun AppNavigation(modifier: Modifier = Modifier) {
    val navController = rememberNavController()
    NavHost(
        navController = navController,
        startDestination = "login",
        modifier = modifier
    ) {
        composable("login") {
            LoginScreen(navController = navController)
        }
        composable("register") {
            RegisterScreen(navController = navController)
        }
        composable(
            "welcome/{username}/{semester}",
            arguments = listOf(
                navArgument("username") { type = NavType.StringType },
                navArgument("semester") { type = NavType.StringType }
            )
        ) { backStackEntry ->
            WelcomeScreen(
                navController = navController,
                username = backStackEntry.arguments?.getString("username"),
                semester = backStackEntry.arguments?.getString("semester")
            )
        }
        composable(
            "admin_dashboard/{username}",
            arguments = listOf(
                navArgument("username") { type = NavType.StringType }
            )
        ) { backStackEntry ->
            AdminDashboardScreen(
                navController = navController,
                username = backStackEntry.arguments?.getString("username")
            )
        }
        composable(
            "manage_student_grades/{studentUsername}/{studentFullName}/{semester}",
            arguments = listOf(
                navArgument("studentUsername") { type = NavType.StringType },
                navArgument("studentFullName") { type = NavType.StringType },
                navArgument("semester") { type = NavType.StringType }
            )
        ) { backStackEntry ->
            val studentUsername = backStackEntry.arguments?.getString("studentUsername")
            val studentFullName = backStackEntry.arguments?.getString("studentFullName")?.let {
                URLDecoder.decode(it, StandardCharsets.UTF_8.name())
            }
            val semester = backStackEntry.arguments?.getString("semester")

            ManageStudentGradesScreen(
                navController = navController,
                studentUsername = studentUsername,
                studentFullName = studentFullName,
                semester = semester
            )
        }
        composable("forgot_password") {
            ForgotPasswordScreen(navController = navController)
        }
        composable(
            "semester_details/{username}/{semester}",
            arguments = listOf(
                navArgument("username") { type = NavType.StringType },
                navArgument("semester") { type = NavType.StringType }
            )
        ) { backStackEntry ->
            SemesterDetailsScreen(
                navController = navController,
                username = backStackEntry.arguments?.getString("username"),
                semester = backStackEntry.arguments?.getString("semester")
            )
        }
        composable(
            "schedule/{username}",
            arguments = listOf(navArgument("username") { type = NavType.StringType })
        ) { backStackEntry ->
            ScheduleScreen(
                navController = navController,
                username = backStackEntry.arguments?.getString("username")
            )
        }
        composable(
            "profile/{username}",
            arguments = listOf(navArgument("username") { type = NavType.StringType })
        ) { backStackEntry ->
            ProfileScreen(
                navController = navController,
                username = backStackEntry.arguments?.getString("username")
            )
        }
        composable("reports") {
            ReportsScreen(navController = navController)
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(navController: NavController, modifier: Modifier = Modifier) {
    var username by remember { mutableStateOf("admin") }
    var password by remember { mutableStateOf("12345678") }
    var passwordVisible by remember { mutableStateOf(false) }
    var usernameError by remember { mutableStateOf<String?>(null) }
    var passwordError by remember { mutableStateOf<String?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    var semesters by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedSemester by remember { mutableStateOf("") }
    var semesterError by remember { mutableStateOf<String?>(null) }
    var semestersLoading by remember { mutableStateOf(true) }
    var expanded by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        try {
            val response = RetrofitClient.instance.getSemesters()
            if (response.isSuccessful) {
                semesters = response.body() ?: emptyList()
                if (semesters.isNotEmpty()) {
                    selectedSemester = semesters[0]
                }
            } else {
                semesterError = "No se pudieron cargar los semestres."
            }
        } catch (e: Exception) {
            semesterError = "Error de red al cargar semestres."
        } finally {
            semestersLoading = false
        }
    }

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally,
            modifier = Modifier.padding(16.dp)
        ) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(8.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.primary)
            ) {
                Text(
                    text = "SISTEMA DE NOTAS - ESTUDIANTES DE DIVINO JESUS DE SANTO TOMAS",
                    modifier = Modifier
                        .padding(16.dp)
                        .fillMaxWidth(),
                    color = MaterialTheme.colorScheme.onPrimary
                )
            }

            Spacer(modifier = Modifier.height(24.dp))

            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(8.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    Text("Semestre:", color = MaterialTheme.colorScheme.onSurface)
                    Spacer(modifier = Modifier.width(8.dp))
                    ExposedDropdownMenuBox(
                        expanded = expanded,
                        onExpandedChange = { if (!isLoading && !semestersLoading) expanded = !expanded },
                        modifier = Modifier.weight(1f)
                    ) {
                        OutlinedTextField(
                            modifier = Modifier.menuAnchor().fillMaxWidth(),
                            value = if (semestersLoading) "Cargando..." else selectedSemester,
                            onValueChange = {},
                            readOnly = true,
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                            enabled = !isLoading && !semestersLoading,
                            isError = semesterError != null
                        )
                        ExposedDropdownMenu(
                            expanded = expanded,
                            onDismissRequest = { expanded = false },
                        ) {
                            semesters.forEach { selectionOption ->
                                DropdownMenuItem(
                                    text = { Text(selectionOption) },
                                    onClick = {
                                        selectedSemester = selectionOption
                                        expanded = false
                                    }
                                )
                            }
                        }
                    }
                }
                if (semesterError != null) {
                    Text(
                        text = semesterError!!,
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp)
                    )
                }
            }

            Spacer(modifier = Modifier.height(24.dp))

            Card(
                modifier = Modifier.width(300.dp),
                shape = RoundedCornerShape(8.dp),
                colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Column(
                        modifier = Modifier.padding(16.dp),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "Iniciar sesión",
                            fontSize = 20.sp,
                            modifier = Modifier
                                .background(MaterialTheme.colorScheme.primary)
                                .padding(12.dp)
                                .fillMaxWidth(),
                            color = MaterialTheme.colorScheme.onPrimary
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        OutlinedTextField(
                            value = username,
                            onValueChange = {
                                username = it
                                usernameError = null
                            },
                            label = { Text("Usuario:") },
                            modifier = Modifier.fillMaxWidth(),
                            isError = usernameError != null,
                            supportingText = {
                                if (usernameError != null) {
                                    Text(usernameError!!, color = MaterialTheme.colorScheme.error)
                                }
                            },
                            enabled = !isLoading
                        )
                        Spacer(modifier = Modifier.height(8.dp))
                        OutlinedTextField(
                            value = password,
                            onValueChange = {
                                password = it
                                passwordError = null
                            },
                            label = { Text("Contraseña:") },
                            visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                            modifier = Modifier.fillMaxWidth(),
                            isError = passwordError != null,
                            supportingText = {
                                if (passwordError != null) {
                                    Text(passwordError!!, color = MaterialTheme.colorScheme.error)
                                }
                            },
                            trailingIcon = {
                                val image = if (passwordVisible)
                                    Icons.Filled.Visibility
                                else Icons.Filled.VisibilityOff

                                val description = if (passwordVisible) "Ocultar contraseña" else "Mostrar contraseña"

                                IconButton(onClick = { passwordVisible = !passwordVisible }) {
                                    Icon(imageVector = image, description)
                                }
                            },
                            enabled = !isLoading
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Button(
                            onClick = {
                                usernameError = null
                                passwordError = null
                                var hasError = false
                                if (username.isBlank()) {
                                    usernameError = "El usuario no puede estar vacío"
                                    hasError = true
                                }
                                if (password.isBlank()) {
                                    passwordError = "La contraseña no puede estar vacía"
                                    hasError = true
                                }

                                if (hasError) return@Button

                                coroutineScope.launch {
                                    isLoading = true
                                    try {
                                        val response = RetrofitClient.instance.login(username, password)

                                        if (response.isSuccessful && response.body()?.status == "success") {
                                            val role = response.body()?.role
                                            if (role == "admin") {
                                                navController.navigate("admin_dashboard/$username") {
                                                    popUpTo("login") { inclusive = true }
                                                }
                                            } else {
                                                if (selectedSemester.isBlank()) {
                                                    Toast.makeText(context, "Por favor, selecciona un semestre.", Toast.LENGTH_SHORT).show()
                                                    return@launch
                                                }
                                                navController.navigate("welcome/$username/$selectedSemester") {
                                                    popUpTo("login") { inclusive = true }
                                                }
                                            }
                                        } else {
                                            val errorMessage = response.body()?.message ?: "Error desconocido"
                                            Toast.makeText(context, errorMessage, Toast.LENGTH_SHORT).show()
                                        }
                                    } catch (e: Exception) {
                                        Toast.makeText(context, "Error de red: ${e.message}", Toast.LENGTH_SHORT).show()
                                    } finally {
                                        isLoading = false
                                    }
                                }
                            },
                            modifier = Modifier.fillMaxWidth(),
                            enabled = !isLoading && !semestersLoading
                        ) {
                            Text("Iniciar sesión")
                        }
                        TextButton(
                            onClick = { navController.navigate("register") },
                            enabled = !isLoading
                        ) {
                            Text("¿No tienes una cuenta? Regístrate")
                        }
                        TextButton(
                            onClick = { navController.navigate("forgot_password") },
                            enabled = !isLoading
                        ) {
                            Text("Olvidó su contraseña?")
                        }
                    }
                    if (isLoading) {
                        CircularProgressIndicator()
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RegisterScreen(navController: NavController, modifier: Modifier = Modifier) {
    var username by remember { mutableStateOf("") }
    var fullName by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var passwordVisible by remember { mutableStateOf(false) }
    var isLoading by remember { mutableStateOf(false) }
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Crear Cuenta") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = modifier
                .padding(innerPadding)
                .padding(16.dp)
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            OutlinedTextField(
                value = username,
                onValueChange = { username = it },
                label = { Text("Usuario") },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading
            )
            Spacer(modifier = Modifier.height(8.dp))
            OutlinedTextField(
                value = fullName,
                onValueChange = { fullName = it },
                label = { Text("Nombre Completo") },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading
            )
            Spacer(modifier = Modifier.height(8.dp))
            OutlinedTextField(
                value = email,
                onValueChange = { email = it },
                label = { Text("Correo Electrónico") },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading
            )
            Spacer(modifier = Modifier.height(8.dp))
            OutlinedTextField(
                value = password,
                onValueChange = { password = it },
                label = { Text("Contraseña") },
                visualTransformation = if (passwordVisible) VisualTransformation.None else PasswordVisualTransformation(),
                modifier = Modifier.fillMaxWidth(),
                trailingIcon = {
                    val image = if (passwordVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff
                    IconButton(onClick = { passwordVisible = !passwordVisible }) {
                        Icon(imageVector = image, contentDescription = if (passwordVisible) "Ocultar" else "Mostrar")
                    }
                },
                enabled = !isLoading
            )
            Spacer(modifier = Modifier.height(24.dp))
            Button(
                onClick = {
                    if (username.isBlank() || password.isBlank() || fullName.isBlank() || email.isBlank()) {
                        Toast.makeText(context, "Todos los campos son obligatorios", Toast.LENGTH_SHORT).show()
                        return@Button
                    }

                    coroutineScope.launch {
                        isLoading = true
                        try {
                            val body = RegisterBody(username, fullName, email, password)
                            val response = RetrofitClient.instance.registerUser(body)
                            if (response.isSuccessful && response.body()?.status == "success") {
                                Toast.makeText(context, "¡Registro exitoso! Por favor, inicia sesión.", Toast.LENGTH_LONG).show()
                                navController.popBackStack()
                            } else {
                                val error = response.body()?.message ?: "Error desconocido en el registro"
                                Toast.makeText(context, error, Toast.LENGTH_LONG).show()
                            }
                        } catch (e: Exception) {
                            Toast.makeText(context, "Error de red: ${e.message}", Toast.LENGTH_LONG).show()
                        } finally {
                            isLoading = false
                        }
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = !isLoading
            ) {
                if (isLoading) {
                    CircularProgressIndicator(modifier = Modifier.size(24.dp), color = Color.White)
                } else {
                    Text("Registrarse")
                }
            }
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ForgotPasswordScreen(navController: NavController, modifier: Modifier = Modifier) {
    var email by remember { mutableStateOf("") }
    val context = LocalContext.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Recuperar Contraseña") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = modifier
                .padding(innerPadding)
                .padding(16.dp)
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            OutlinedTextField(
                value = email,
                onValueChange = { email = it },
                label = { Text("Correo electrónico") },
                modifier = Modifier.fillMaxWidth()
            )
            Spacer(modifier = Modifier.height(16.dp))
            Button(
                onClick = {
                    if (email.isNotBlank()) {
                        Toast.makeText(context, "Se han enviado las instrucciones a $email", Toast.LENGTH_SHORT).show()
                        navController.popBackStack()
                    } else {
                        Toast.makeText(context, "Por favor, introduce tu correo", Toast.LENGTH_SHORT).show()
                    }
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("Enviar")
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WelcomeScreen(navController: NavController, username: String?, semester: String?, modifier: Modifier = Modifier) {
    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Panel del Estudiante") },
                actions = {
                    IconButton(onClick = {
                        navController.navigate("login") {
                            popUpTo(navController.graph.startDestinationId) { inclusive = true }
                        }
                    }) {
                        Icon(Icons.AutoMirrored.Filled.Logout, contentDescription = "Cerrar sesión")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = modifier
                .padding(innerPadding)
                .padding(16.dp)
                .fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Text("¡Bienvenido, ${username ?: "Usuario"}!", fontSize = 24.sp, fontWeight = FontWeight.Bold)
            Spacer(modifier = Modifier.height(8.dp))
            Text(semester ?: "", fontSize = 16.sp, color = MaterialTheme.colorScheme.secondary)
            Spacer(modifier = Modifier.height(32.dp))

            // Menu options
            DashboardButton(text = "Cursos y Calificaciones", icon = Icons.Default.School) {
                if (username != null && semester != null) {
                    navController.navigate("semester_details/$username/$semester")
                }
            }
            Spacer(modifier = Modifier.height(16.dp))
            DashboardButton(text = "Mi Horario", icon = Icons.Default.Schedule) {
                username?.let { user -> navController.navigate("schedule/$user") }
            }
            Spacer(modifier = Modifier.height(16.dp))
            DashboardButton(text = "Perfil", icon = Icons.Default.Person) {
                username?.let { user -> navController.navigate("profile/$user") }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdminDashboardScreen(navController: NavController, username: String?, modifier: Modifier = Modifier) {
    var students by remember { mutableStateOf<List<Student>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    var semesters by remember { mutableStateOf<List<String>>(emptyList()) }
    var selectedSemester by remember { mutableStateOf("") }
    var semesterError by remember { mutableStateOf<String?>(null) }
    var semestersLoading by remember { mutableStateOf(true) }
    var expanded by remember { mutableStateOf(false) }
    val context = LocalContext.current

    LaunchedEffect(Unit) {
        isLoading = true
        semestersLoading = true
        try {
            val studentsResponse = RetrofitClient.instance.getStudents()
            if (studentsResponse.isSuccessful) {
                students = studentsResponse.body() ?: emptyList()
            } else {
                errorMessage = "Error al cargar la lista de estudiantes."
            }

            val semestersResponse = RetrofitClient.instance.getSemesters()
            if (semestersResponse.isSuccessful) {
                semesters = semestersResponse.body() ?: emptyList()
                if (semesters.isNotEmpty()) {
                    selectedSemester = semesters[0]
                }
            } else {
                semesterError = "No se pudieron cargar los semestres."
            }

        } catch (e: Exception) {
            errorMessage = "Error de red: ${e.message}"
        } finally {
            isLoading = false
            semestersLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Panel de Administrador") },
                actions = {
                    IconButton(onClick = {
                        navController.navigate("login") {
                            popUpTo(navController.graph.startDestinationId) { inclusive = true }
                        }
                    }) {
                        Icon(Icons.AutoMirrored.Filled.Logout, contentDescription = "Cerrar sesión")
                    }
                }
            )
        }
    ) { innerPadding ->
        Column(
            modifier = modifier
                .padding(innerPadding)
                .fillMaxSize()
        ) {
            // Semester Selector
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text("Semestre:", modifier = Modifier.padding(end = 8.dp))
                ExposedDropdownMenuBox(
                    expanded = expanded,
                    onExpandedChange = { expanded = !semestersLoading && !expanded },
                    modifier = Modifier.weight(1f)
                ) {
                    OutlinedTextField(
                        modifier = Modifier.menuAnchor().fillMaxWidth(),
                        value = if (semestersLoading) "Cargando..." else selectedSemester,
                        onValueChange = {},
                        readOnly = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                        enabled = !semestersLoading
                    )
                    ExposedDropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false },
                    ) {
                        semesters.forEach { selectionOption ->
                            DropdownMenuItem(
                                text = { Text(selectionOption) },
                                onClick = {
                                    selectedSemester = selectionOption
                                    expanded = false
                                }
                            )
                        }
                    }
                }
            }

            Button(
                onClick = { navController.navigate("reports") },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp, vertical = 8.dp)
            ) {
                Text("Generar Reportes")
            }

            Divider()

            Box(modifier = Modifier.weight(1f), contentAlignment = Alignment.Center) {
                when {
                    isLoading -> {
                        CircularProgressIndicator()
                    }
                    errorMessage != null -> {
                        Text(text = errorMessage!!, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
                    }
                    students.isEmpty() -> {
                        Text("No hay estudiantes registrados.", fontSize = 18.sp, modifier = Modifier.padding(16.dp))
                    }
                    else -> {
                        LazyColumn(
                            contentPadding = PaddingValues(16.dp),
                            verticalArrangement = Arrangement.spacedBy(16.dp),
                            modifier = Modifier.fillMaxSize()
                        ) {
                            item {
                                Text("Lista de Estudiantes", style = MaterialTheme.typography.headlineSmall)
                                Spacer(modifier = Modifier.height(8.dp))
                            }
                            items(students) { student ->
                                StudentCard(student = student, onManageClick = {
                                    if (selectedSemester.isBlank()) {
                                        Toast.makeText(context, "Por favor, selecciona un semestre primero.", Toast.LENGTH_SHORT).show()
                                    } else {
                                        val encodedFullName = URLEncoder.encode(student.fullName, StandardCharsets.UTF_8.name())
                                        navController.navigate("manage_student_grades/${student.username}/$encodedFullName/$selectedSemester")
                                    }
                                })
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ManageStudentGradesScreen(
    navController: NavController,
    studentUsername: String?,
    studentFullName: String?,
    semester: String?,
    modifier: Modifier = Modifier
) {
    var coursesWithGrades by remember { mutableStateOf<List<CourseWithGrades>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    var showDialog by remember { mutableStateOf(false) }
    var selectedGrade by remember { mutableStateOf<Grade?>(null) }
    val context = LocalContext.current
    val coroutineScope = rememberCoroutineScope()

    // Function to reload data
    val loadData = { // this is a lambda
        if (studentUsername.isNullOrBlank() || semester.isNullOrBlank()) {
            errorMessage = "Usuario o semestre no especificado."
        } else {
            isLoading = true
            coroutineScope.launch {
                try {
                    val response = RetrofitClient.instance.getSemesterDetails(studentUsername, semester)
                    if (response.isSuccessful) {
                        coursesWithGrades = response.body() ?: emptyList()
                        errorMessage = null
                    } else {
                        errorMessage = "Error al cargar los detalles del semestre: ${response.message()}"
                    }
                } catch (e: Exception) {
                    errorMessage = "Error de red: ${e.message}"
                } finally {
                    isLoading = false
                }
            }
        }
    }

    LaunchedEffect(studentUsername, semester) {
        loadData()
    }

    if (showDialog && selectedGrade != null) {
        UpdateGradeDialog(
            grade = selectedGrade!!,
            onDismiss = { showDialog = false },
            onSave = {
                coroutineScope.launch {
                    try {
                        val response = RetrofitClient.instance.updateGrade(it)
                        if (response.isSuccessful && response.body()?.status == "success") {
                            Toast.makeText(context, "Nota actualizada con éxito", Toast.LENGTH_SHORT).show()
                            loadData() // Recargar datos
                        } else {
                            val error = response.body()?.message ?: "Error desconocido"
                            Toast.makeText(context, "Error: $error", Toast.LENGTH_LONG).show()
                        }
                    } catch (e: Exception) {
                        Toast.makeText(context, "Error de red: ${e.message}", Toast.LENGTH_LONG).show()
                    }
                    showDialog = false
                }
            }
        )
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(studentFullName ?: "Gestionar Notas") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Box(
            modifier = modifier
                .padding(innerPadding)
                .fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            when {
                isLoading -> {
                    CircularProgressIndicator()
                }
                errorMessage != null -> {
                    Text(text = errorMessage!!, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
                }
                coursesWithGrades.isEmpty() -> {
                    Text("Este estudiante no tiene cursos para el semestre '$semester'.", fontSize = 18.sp, modifier = Modifier.padding(16.dp))
                }
                else -> {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        items(coursesWithGrades) { course ->
                            AdminCourseCard(course = course, onGradeClick = {
                                selectedGrade = it
                                showDialog = true
                            })
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun UpdateGradeDialog(grade: Grade, onDismiss: () -> Unit, onSave: (GradeUpdateBody) -> Unit) {
    var newGradeValue by remember { mutableStateOf(grade.value) }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(text = "Actualizar Nota") },
        text = {
            Column {
                Text("Editando nota para: ${grade.name}")
                Spacer(modifier = Modifier.height(16.dp))
                OutlinedTextField(
                    value = newGradeValue,
                    onValueChange = { newGradeValue = it },
                    label = { Text("Nueva Calificación (0-20)") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal)
                )
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    val updateBody = GradeUpdateBody(gradeId = grade.id, gradeValue = newGradeValue)
                    onSave(updateBody)
                }
            ) {
                Text("Guardar")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancelar")
            }
        }
    )
}


@Composable
fun StudentCard(student: Student, onManageClick: () -> Unit) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.Center) {
                Text(text = student.fullName, style = MaterialTheme.typography.titleMedium)
                Text(text = "@${student.username}", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
            }
            Button(onClick = onManageClick) {
                Text("Gestionar")
            }
        }
    }
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SemesterDetailsScreen(navController: NavController, username: String?, semester: String?, modifier: Modifier = Modifier) {
    var coursesWithGrades by remember { mutableStateOf<List<CourseWithGrades>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(key1 = username, key2 = semester) {
        if (username.isNullOrBlank() || semester.isNullOrBlank()) {
            errorMessage = "Usuario o semestre no especificado."
            return@LaunchedEffect
        }
        isLoading = true
        try {
            val response = RetrofitClient.instance.getSemesterDetails(username, semester)
            if (response.isSuccessful) {
                coursesWithGrades = response.body() ?: emptyList()
            } else {
                errorMessage = "Error al cargar los detalles del semestre: ${response.message()}"
            }
        } catch (e: Exception) {
            errorMessage = "Error de red: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Cursos y Calificaciones") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Box(
            modifier = modifier
                .padding(innerPadding)
                .fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            when {
                isLoading -> {
                    CircularProgressIndicator()
                }
                errorMessage != null -> {
                    Text(text = errorMessage!!, color = MaterialTheme.colorScheme.error)
                }
                coursesWithGrades.isEmpty() -> {
                    Text("No estás inscrito en cursos para este semestre.", fontSize = 18.sp, modifier = Modifier.padding(16.dp))
                }
                else -> {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        items(coursesWithGrades) { course ->
                            CourseWithGradesCard(course = course)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun CourseWithGradesCard(course: CourseWithGrades) {
    var expanded by remember { mutableStateOf(false) }
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { expanded = !expanded },
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(text = course.name, style = MaterialTheme.typography.titleLarge)
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(text = course.professor, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
                }
                Icon(
                    imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                    contentDescription = if (expanded) "Contraer" else "Expandir"
                )
            }
            AnimatedVisibility(visible = expanded) {
                Column(modifier = Modifier.padding(top = 16.dp)) {
                    if (course.grades.isEmpty()) {
                        Text("No hay calificaciones registradas para este curso.")
                    } else {
                        course.grades.forEach {
                            GradeItem(grade = it)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun AdminCourseCard(course: CourseWithGrades, onGradeClick: (Grade) -> Unit) {
    var expanded by remember { mutableStateOf(true) } // Default to expanded
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Column(modifier = Modifier.padding(16.dp)) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clickable { expanded = !expanded },
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(text = course.name, style = MaterialTheme. typography.titleLarge)
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(text = course.professor, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
                }
                Icon(
                    imageVector = if (expanded) Icons.Default.ExpandLess else Icons.Default.ExpandMore,
                    contentDescription = if (expanded) "Contraer" else "Expandir"
                )
            }
            AnimatedVisibility(visible = expanded) {
                Column(modifier = Modifier.padding(top = 16.dp)) {
                    if (course.grades.isEmpty()) {
                        Text("No hay calificaciones registradas para este curso.")
                    } else {
                        course.grades.forEach { grade ->
                            EditableGradeItem(grade = grade, onClick = { onGradeClick(grade) })
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun GradeItem(grade: Grade) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = grade.name, style = MaterialTheme.typography.bodyLarge)
        Text(text = grade.value, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold)
    }
    Divider()
}

@Composable
private fun EditableGradeItem(grade: Grade, onClick: () -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick)
            .padding(vertical = 8.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(text = grade.name, style = MaterialTheme.typography.bodyLarge)
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(text = grade.value, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.Bold)
            Spacer(modifier = Modifier.width(8.dp))
            Icon(Icons.Default.Edit, contentDescription = "Editar Nota", tint = MaterialTheme.colorScheme.primary)
        }
    }
    Divider()
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ScheduleScreen(navController: NavController, username: String?, modifier: Modifier = Modifier) {
    var scheduleByDay by remember { mutableStateOf<Map<String, List<ScheduleItem>>>(emptyMap()) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    val orderedDays = listOf("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo")


    LaunchedEffect(key1 = username) {
        if (username.isNullOrBlank()) {
            errorMessage = "Usuario no especificado."
            return@LaunchedEffect
        }
        isLoading = true
        try {
            val response = RetrofitClient.instance.getSchedule(username)
            if (response.isSuccessful) {
                scheduleByDay = response.body() ?: emptyMap()
            } else {
                errorMessage = "Error al cargar el horario: ${response.message()}"
            }
        } catch (e: Exception) {
            errorMessage = "Error de red: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Mi Horario") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Box(
            modifier = modifier
                .padding(innerPadding)
                .fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            when {
                isLoading -> {
                    CircularProgressIndicator()
                }
                errorMessage != null -> {
                    Text(text = errorMessage!!, color = MaterialTheme.colorScheme.error)
                }
                scheduleByDay.isEmpty() -> {
                    Text("No tienes un horario registrado.", fontSize = 18.sp)
                }
                else -> {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize(),
                        contentPadding = PaddingValues(16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        val sortedDays = scheduleByDay.keys.sortedBy { orderedDays.indexOf(it) }
                        sortedDays.forEach { day ->
                            item {
                                Text(
                                    text = day,
                                    style = MaterialTheme.typography.headlineSmall,
                                    modifier = Modifier.padding(top = 8.dp, bottom = 8.dp)
                                )
                            }
                            items(scheduleByDay[day] ?: emptyList()) { scheduleItem ->
                                ScheduleItemCard(scheduleItem = scheduleItem)
                            }
                        }
                    }
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ProfileScreen(navController: NavController, username: String?, modifier: Modifier = Modifier) {
    var userProfile by remember { mutableStateOf<UserProfile?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }

    LaunchedEffect(key1 = username) {
        if (username.isNullOrBlank()) {
            errorMessage = "Usuario no especificado."
            return@LaunchedEffect
        }
        isLoading = true
        try {
            val response = RetrofitClient.instance.getProfile(username)
            if (response.isSuccessful) {
                userProfile = response.body()
            } else {
                errorMessage = "Error al cargar el perfil: ${response.message()}"
            }
        } catch (e: Exception) {
            errorMessage = "Error de red: ${e.message}"
        } finally {
            isLoading = false
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Mi Perfil") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Atrás")
                    }
                }
            )
        }
    ) { innerPadding ->
        Box(
            modifier = modifier
                .padding(innerPadding)
                .fillMaxSize(),
            contentAlignment = Alignment.Center
        ) {
            when {
                isLoading -> {
                    CircularProgressIndicator()
                }
                errorMessage != null -> {
                    Text(text = errorMessage!!, color = MaterialTheme.colorScheme.error, modifier = Modifier.padding(16.dp))
                }
                userProfile == null -> {
                    Text("No se pudo cargar el perfil.", fontSize = 18.sp, modifier = Modifier.padding(16.dp))
                }
                else -> {
                    ProfileCard(userProfile = userProfile!!)
                }
            }
        }
    }
}

@Composable
private fun ProfileCard(userProfile: UserProfile) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .padding(16.dp),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            ProfileInfoRow(label = "Usuario", value = userProfile.username, icon = Icons.Default.Person)
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            ProfileInfoRow(label = "Nombre Completo", value = userProfile.fullName, icon = Icons.Default.Badge)
            Divider(modifier = Modifier.padding(vertical = 8.dp))
            ProfileInfoRow(label = "Email", value = userProfile.email, icon = Icons.Default.Email)
        }
    }
}

@Composable
private fun ProfileInfoRow(label: String, value: String, icon: ImageVector) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = label,
            tint = MaterialTheme.colorScheme.primary,
            modifier = Modifier.size(24.dp)
        )
        Spacer(modifier = Modifier.width(16.dp))
        Column {
            Text(text = label, style = MaterialTheme.typography.labelMedium)
            Text(text = value, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.SemiBold)
        }
    }
}

@Composable
private fun ScheduleItemCard(scheduleItem: ScheduleItem) {
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(8.dp),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(text = scheduleItem.courseName, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold)
                Spacer(modifier = Modifier.height(4.dp))
                Text(text = scheduleItem.classroom, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
            }
            Column(horizontalAlignment = Alignment.End) {
                Text(text = scheduleItem.startTime, style = MaterialTheme.typography.bodyLarge)
                Text(text = scheduleItem.endTime, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.secondary)
            }
        }
    }
}

@Composable
private fun DashboardButton(text: String, icon: ImageVector, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .height(60.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Icon(icon, contentDescription = text)
            Spacer(modifier = Modifier.width(16.dp))
            Text(text, fontSize = 18.sp)
        }
    }
}


@Preview(showBackground = true)
@Composable
fun LoginScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        LoginScreen(navController)
    }
}

@Preview(showBackground = true)
@Composable
fun RegisterScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        RegisterScreen(navController)
    }
}

@Preview(showBackground = true)
@Composable
fun WelcomeScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        WelcomeScreen(navController, "admin", "2024-I")
    }
}

@Preview(showBackground = true)
@Composable
fun AdminDashboardScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        AdminDashboardScreen(navController, "admin")
    }
}

@Preview(showBackground = true)
@Composable
fun ManageStudentGradesScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        ManageStudentGradesScreen(navController, "testuser", "Test User Full Name", "2024-I")
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Preview(showBackground = true)
@Composable
fun ForgotPasswordScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        ForgotPasswordScreen(navController)
    }
}

@Preview(showBackground = true)
@Composable
fun SemesterDetailsScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        SemesterDetailsScreen(navController, "admin", "2024-I")
    }
}


@Preview(showBackground = true)
@Composable
fun ScheduleScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        ScheduleScreen(navController, "admin")
    }
}

@Preview(showBackground = true)
@Composable
fun ProfileScreenPreview() {
    Los_chatosTheme {
        val navController = rememberNavController()
        ProfileScreen(navController, "admin")
    }
}
