@file:Suppress("HardCodedStringLiteral")

package eu.gaudian.translator.view.exercises

import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Exercise
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppAlertDialog
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedCard
import eu.gaudian.translator.view.composable.AppTabLayout
import eu.gaudian.translator.view.composable.DialogButton
import eu.gaudian.translator.view.composable.Screen
import eu.gaudian.translator.view.composable.TabItem
import eu.gaudian.translator.viewmodel.AiGenerationState
import eu.gaudian.translator.viewmodel.ExerciseViewModel

/**
 * Defines the tabs for the main Exercise screen, replacing the enum from ExerciseFragment.
 */
enum class ExerciseTab(override val title: String, override val icon: ImageVector) : TabItem {
    Dashboard("Dashboard", AppIcons.Dashboard),
    AllExercises("All Exercises", AppIcons.BarChart)
}

/**
 * This screen replaces ExerciseFragment. It acts as the main entry point for the "Exercises" tab,
 * showing a tabbed layout for the dashboard and the list of all exercises.
 *
 * @param navController The main NavController to handle navigation to an exercise session.
 */
@Composable
fun MainExerciseScreen(
    navController: NavController,
) {
    val activity = LocalContext.current.findActivity()
    val exerciseViewModel : ExerciseViewModel = hiltViewModel(activity)
    val aiState by exerciseViewModel.aiGenerationState.collectAsState()
    var exerciseToDelete by remember { mutableStateOf<Exercise?>(null) }
    var showGenerateDialog by remember { mutableStateOf(false) }

    // This outer 'when' handles the AI generation state, same as in the fragment.
    when (val currentState = aiState) {
        is AiGenerationState.Idle -> {
            var selectedTab by remember { mutableStateOf<TabItem>(ExerciseTab.Dashboard) }

            Box(modifier = Modifier.fillMaxSize()) {
                    Column(modifier = Modifier.fillMaxSize()) {
                        AppTabLayout(
                            tabs = ExerciseTab.entries,
                            selectedTab = selectedTab,
                            onTabSelected = { selectedTab = it },
                            onNavigateBack = {
                                if (!navController.popBackStack()) {
                                    navController.navigate(Screen.Home.route) {
                                        launchSingleTop = true
                                        restoreState = false
                                    }
                                }
                            }
                        )

                        Box(modifier = Modifier.weight(1f)) {
                            when (selectedTab) {
                                ExerciseTab.Dashboard -> ExerciseDashboard(
                                    onCreateExercise = { showGenerateDialog = true }
                                )
                                ExerciseTab.AllExercises -> ExerciseListScreen(
                                    onExerciseClicked = { exercise ->
                                        exerciseViewModel.startExercise(exercise)
                                        navController.navigate("exercise_session")
                                    },
                                    onDeleteClicked = { exercise ->
                                        exerciseToDelete = exercise
                                    },
                                    onLongExerciseClicked = { exercise ->
                                        exerciseToDelete = exercise // Open delete dialog on long press
                                    },
                                )
                            }

                        }
                    }

            ExerciseMenu(
                modifier = Modifier
                        .align(Alignment.BottomEnd)
                    .padding(16.dp),
                onCreateExercise = { showGenerateDialog = true },
                onCreateYouTubeExercise = {
                    // Navigate to YouTube browser and keep MainExerciseScreen in the back stack
                    navController.navigate("youtube_browse")
                },
                onStartExercise = { } //TODO
            )

            }
            if (showGenerateDialog) {
                GenerateExerciseDialog(
                    onDismiss = {
                        @Suppress("AssignedValueIsNeverRead")
                        showGenerateDialog = false
                    },
                    onGenerate = { category, types, difficulty, amount, sourceLanguage, targetLanguage ->
                        exerciseViewModel.generateExerciseWithAi(category, types, difficulty, amount, sourceLanguage, targetLanguage)
                    }
                )
            }


            exerciseToDelete?.let { exercise ->
                DeleteConfirmationDialog(
                    exercise = exercise,
                    onConfirm = {
                        // Assuming the Exercise model has a string or numeric ID
                        exerciseViewModel.deleteExercise(exercise.id)
                    },
                    onDismiss = {
                        @Suppress("AssignedValueIsNeverRead")
                        exerciseToDelete = null
                    }
                )
            }
        }
        else -> {
            AiGenerationScreen(state = currentState)
        }
    }
}

@Composable
private fun DeleteConfirmationDialog(
    exercise: Exercise,
    onConfirm: () -> Unit,
    onDismiss: () -> Unit
) {
    AppAlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("Delete Exercise") },
        text = { Text("Are you sure you want to delete the exercise \"${exercise.title}\"? This action cannot be undone.") },
        confirmButton = {
            DialogButton(
                onClick = {
                    onConfirm()
                    onDismiss()
                },
            ) {
                Text("Delete")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Cancel")
            }
        }
    )
}

@Composable
private fun ExerciseDashboard(onCreateExercise: () -> Unit) {
    AppOutlinedCard{
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(id = R.drawable.ic_icon_construction),
            contentDescription = null,
            modifier = Modifier.size(200.dp),
        )
        Spacer(modifier = Modifier.height(16.dp))
        Text(
            "Danger Zone",
            style = MaterialTheme.typography.headlineMedium
        )
        Text(
            "This area is under construction, exercises are in a beta state and may not work as expected.",
            style = MaterialTheme.typography.bodyLarge,
            modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
        )
        AppButton(onClick = onCreateExercise) {
            Icon(AppIcons.Add, contentDescription = null, modifier = Modifier.padding(end = 8.dp))
            Text("Generate New Exercise")
        }
    }
    }
}