@file:Suppress("AssignedValueIsNeverRead")

package eu.gaudian.translator.view.exercises

import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.FilterChip
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.mutableFloatStateOf
import androidx.compose.runtime.mutableIntStateOf
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.draw.alpha
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Question
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.DialogButton
import eu.gaudian.translator.view.composable.SourceLanguageDropdown
import eu.gaudian.translator.view.composable.TargetLanguageDropdown
import eu.gaudian.translator.viewmodel.LanguageViewModel
import kotlin.math.roundToInt
import kotlin.reflect.KClass

@SuppressLint("FrequentlyChangingValue")
@Composable
fun GenerateExerciseDialog(
    onDismiss: () -> Unit,
    onGenerate: (category: String, types: List<KClass<out Question>>, difficulty: String, amount: Int, sourceLanguage: String?, targetLanguage: String?) -> Unit
) {
    // Orchestrator for a compact 2-step flow
    var step by remember { mutableIntStateOf(1) }
    val activity = LocalContext.current.findActivity()


    var category by remember { mutableStateOf("") }
    var amount by remember { mutableFloatStateOf(10f) }
    var difficulty by remember { mutableFloatStateOf(1f) } // 0=Easy, 1=Medium, 2=Hard
    val questionTypes = Question.allTypes
    var selectedTypes by remember { mutableStateOf(questionTypes.toSet()) }

    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val sourceLang = languageViewModel.selectedSourceLanguage.collectAsState().value?.name
    val targetLang = languageViewModel.selectedTargetLanguage.collectAsState().value?.name

    val difficultyLabels = listOf(
        stringResource(R.string.label_easy),
        stringResource(R.string.label_medium),
        stringResource(R.string.label_hard)
    )

    when (step) {
        1 -> {
            // Step 1: Basic Info (Category + Languages)
            val isNextEnabled = category.isNotBlank() && !targetLang.isNullOrBlank()
            AppDialog(onDismissRequest = onDismiss) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                ) {
                    Column(modifier = Modifier.padding(8.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
                        Text(
                            text = stringResource(R.string.text_generate_exercise_with_ai),
                            style = MaterialTheme.typography.titleLarge,
                            color = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        AppOutlinedTextField(
                            value = category,
                            onValueChange = { category = it },
                            label = { Text(stringResource(R.string.text_category_prompt)) },
                            placeholder = { Text(stringResource(R.string.text_e_g_irregular_verbs)) },
                            modifier = Modifier.fillMaxWidth()
                        )
                        Text(stringResource(R.string.text_select_languages), style = MaterialTheme.typography.labelLarge)
                        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                            Box(modifier = Modifier.weight(1f)) {
                                SourceLanguageDropdown(languageViewModel = languageViewModel, autoEnabled = true, iconEnabled = true)
                            }
                            Spacer(modifier = Modifier.width(8.dp))
                            Box(modifier = Modifier.weight(1f)) {
                                TargetLanguageDropdown(languageViewModel = languageViewModel, iconEnabled = true)
                            }
                        }
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 8.dp),
                            horizontalArrangement = Arrangement.End,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            TextButton(onClick = onDismiss) { Text(stringResource(R.string.label_cancel)) }
                            DialogButton(onClick = { step = 2 }, enabled = isNextEnabled) {
                                Text(stringResource(R.string.next))
                            }
                        }
                    }
                }
            }
        }
        else -> {
            // Step 2: Options (Types + Difficulty + Amount) and Generate
            val isGenerateEnabled = category.isNotBlank() && selectedTypes.isNotEmpty() && !targetLang.isNullOrBlank()
            AppDialog(onDismissRequest = { step = 1 }) {
                Card(
                    modifier = Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)
                ) {
                    Column(modifier = Modifier.padding(8.dp), verticalArrangement = Arrangement.spacedBy(16.dp)) {
                        Text(
                            text = stringResource(R.string.text_question_types),
                            style = MaterialTheme.typography.titleLarge,
                            color = MaterialTheme.colorScheme.onSurface,
                            modifier = Modifier.padding(bottom = 8.dp)
                        )
                        Box {
                            val scrollState = rememberScrollState()
                            if (scrollState.canScrollForward) {
                                Box(
                                    modifier = Modifier
                                        .align(Alignment.BottomCenter)
                                        .offset(y = 8.dp)
                                        .fillMaxWidth()
                                        .heightIn(max = 20.dp)
                                        .background(MaterialTheme.colorScheme.surface.copy(alpha = 0.5f))
                                        .alpha(if (scrollState.value < scrollState.maxValue - 50) 1f else (scrollState.maxValue - scrollState.value) / 50f)
                                ) {
                                    Text("...", modifier = Modifier.align(Alignment.Center), color = MaterialTheme.colorScheme.onSurface)
                                }
                            }
                            Box(
                                modifier = Modifier
                                    .heightIn(max = 200.dp)
                                    .verticalScroll(scrollState)
                            ) {
                                FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                                    questionTypes.forEach { type ->
                                        val isSelected = selectedTypes.contains(type)
                                        FilterChip(
                                            selected = isSelected,
                                            onClick = {
                                                selectedTypes = if (isSelected) selectedTypes - type else selectedTypes + type
                                            },
                                            label = { Text(type.simpleName?.replace(stringResource(R.string.text_question), "") ?: "") }
                                        )
                                    }
                                }
                            }
                        }
                        Text(stringResource(R.string.text_difficulty_2d, difficultyLabels[difficulty.roundToInt()]), style = MaterialTheme.typography.labelLarge)
                        AppSlider(value = difficulty, onValueChange = { difficulty = it }, valueRange = 0f..2f, steps = 1)
                        Text(stringResource(R.string.text_amount_2d_questions, amount.roundToInt()), style = MaterialTheme.typography.labelLarge)
                        AppSlider(value = amount, onValueChange = { amount = it }, valueRange = 1f..20f, steps = 18)
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(top = 8.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            TextButton(onClick = { step = 1 }) { Text(stringResource(R.string.cd_back)) }
                            Row(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically) {
                                TextButton(onClick = { step = 1 }) { Text(stringResource(R.string.label_cancel)) }
                                DialogButton(
                                    onClick = {
                                        onGenerate(
                                            category,
                                            selectedTypes.toList(),
                                            difficultyLabels[difficulty.roundToInt()],
                                            amount.roundToInt(),
                                            sourceLang,
                                            targetLang
                                        )
                                        onDismiss()
                                    },
                                    enabled = isGenerateEnabled
                                ) { Text(stringResource(R.string.text_generate)) }
                            }
                        }
                    }
                }
            }
        }
    }
}