package eu.gaudian.translator.view.exercises

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBackIosNew
import androidx.compose.material.icons.filled.CheckCircle
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.outlined.Circle
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.SheetState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.navigation.NavHostController
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.TagCategory
import eu.gaudian.translator.model.VocabularyCategory
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppButton
import eu.gaudian.translator.view.composable.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedButton
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.OptionItemSwitch
import eu.gaudian.translator.view.dialogs.CategoryDropdown
import eu.gaudian.translator.view.vocabulary.VocabularyExerciseType
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyExerciseViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch

@Composable
fun StartExerciseScreen(
    navController: NavHostController,
    modifier: Modifier = Modifier
) {
    val activity = androidx.compose.ui.platform.LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val exerciseViewModel: VocabularyExerciseViewModel = hiltViewModel(viewModelStoreOwner = activity)

    val exerciseConfig by exerciseViewModel.pendingExerciseConfig.collectAsState()
    var selectedLanguagePairs by remember { mutableStateOf<List<Pair<Language, Language>>>(emptyList()) }
    var selectedCategories by remember { mutableStateOf<List<VocabularyCategory>>(emptyList()) }
    var selectedStages by remember { mutableStateOf<List<VocabularyStage>>(emptyList()) }

    var selectedOriginLanguage by remember { mutableStateOf<Language?>(null) }
    var selectedTargetLanguage by remember { mutableStateOf<Language?>(null) }
    val isDirectionPreferenceSet = selectedOriginLanguage != null || selectedTargetLanguage != null

    val selectedPairsIds = remember(selectedLanguagePairs) {
        selectedLanguagePairs.map { it.first.nameResId to it.second.nameResId }
    }
    val selectedCategoryIds = remember(selectedCategories) {
        selectedCategories.map { it.id }
    }

    val filteredItemsFlow = remember(
        selectedPairsIds,
        selectedCategoryIds,
        selectedStages,
        exerciseConfig.dueTodayOnly
    ) {
        vocabularyViewModel.filterVocabularyItemsByPairs(
            languagePairs = selectedPairsIds.ifEmpty { null },
            query = null,
            categoryIds = selectedCategoryIds.ifEmpty { null },
            stages = selectedStages.ifEmpty { null },
            sortOrder = VocabularyViewModel.SortOrder.NEWEST_FIRST,
            dueTodayOnly = exerciseConfig.dueTodayOnly
        )
    }
    val itemsToShow by filteredItemsFlow.collectAsState(initial = emptyList())
    val totalItemCount = itemsToShow.size

    val availableLanguagesFromItems = remember(itemsToShow, selectedPairsIds) {
        val ids = if (selectedPairsIds.isNotEmpty()) {
            selectedPairsIds.flatMap { pair -> listOf(pair.first, pair.second) }.toSet()
        } else {
            itemsToShow.flatMap { listOfNotNull(it.languageFirstId, it.languageSecondId) }.toSet()
        }
        ids
    }

    var amount by remember { mutableIntStateOf(0) }
    androidx.compose.runtime.LaunchedEffect(totalItemCount) {
        amount = totalItemCount
    }

    val updateConfig: (eu.gaudian.translator.viewmodel.ExerciseConfig) -> Unit = { config ->
        exerciseViewModel.updatePendingExerciseConfig(config)
    }

    Box(
        modifier = modifier.fillMaxSize(),
        contentAlignment = Alignment.TopCenter
    ) {
        Column(
            modifier = Modifier
                .widthIn(max = 700.dp) // Keeps it from over-stretching on tablets
                .fillMaxSize()
        ) {
            TopBarSection(
                onBackClick = { navController.popBackStack() },
                shuffleCards = exerciseConfig.shuffleCards,
                onShuffleCardsChanged = { updateConfig(exerciseConfig.copy(shuffleCards = it)) },
                shuffleLanguages = exerciseConfig.shuffleLanguages,
                onShuffleLanguagesChanged = { updateConfig(exerciseConfig.copy(shuffleLanguages = it)) },
                shuffleLanguagesEnabled = !isDirectionPreferenceSet,
                trainingMode = exerciseConfig.trainingMode,
                onTrainingModeChanged = { updateConfig(exerciseConfig.copy(trainingMode = it)) },
            )

            LazyColumn(
                modifier = Modifier
                    .weight(1f)
                    .padding(horizontal = 24.dp),
                verticalArrangement = Arrangement.spacedBy(32.dp)
            ) {
                item { Spacer(modifier = Modifier.height(8.dp)) }
                item {
                    LanguagePairSection(
                        selectedPairs = selectedLanguagePairs,
                        availableLanguageIds = availableLanguagesFromItems,
                        onPairsChanged = { updatedPairs ->
                            val hadPairs = selectedLanguagePairs.isNotEmpty()
                            selectedLanguagePairs = updatedPairs
                            if (updatedPairs.isNotEmpty()) {
                                selectedOriginLanguage = null
                                selectedTargetLanguage = null
                                updateConfig(exerciseConfig.copy(originLanguageId = null, targetLanguageId = null))
                            } else if (hadPairs) {
                                updateConfig(exerciseConfig.copy(originLanguageId = null, targetLanguageId = null))
                            }
                        },
                        onOriginLanguageSelected = { language ->
                            if (language?.nameResId == selectedOriginLanguage?.nameResId) {
                                selectedOriginLanguage = null
                                updateConfig(exerciseConfig.copy(originLanguageId = null))
                            } else {
                                selectedOriginLanguage = language
                                if (selectedTargetLanguage?.nameResId == language?.nameResId) {
                                    selectedTargetLanguage = null
                                    updateConfig(exerciseConfig.copy(targetLanguageId = null))
                                }
                                updateConfig(exerciseConfig.copy(originLanguageId = language?.nameResId))
                            }
                        },
                        onTargetLanguageSelected = { language ->
                            if (language?.nameResId == selectedTargetLanguage?.nameResId) {
                                selectedTargetLanguage = null
                                updateConfig(exerciseConfig.copy(targetLanguageId = null))
                            } else {
                                selectedTargetLanguage = language
                                if (selectedOriginLanguage?.nameResId == language?.nameResId) {
                                    selectedOriginLanguage = null
                                    updateConfig(exerciseConfig.copy(originLanguageId = null))
                                }
                                updateConfig(exerciseConfig.copy(targetLanguageId = language?.nameResId))
                            }
                        },
                        languageSelectionEnabled = true,
                        selectedPairsCount = selectedLanguagePairs.size,
                        selectedOriginLanguage = selectedOriginLanguage,
                        selectedTargetLanguage = selectedTargetLanguage
                    )
                }
                item {
                    CategoriesSection(
                        selectedCategories = selectedCategories,
                        onCategoriesChanged = { selectedCategories = it }
                    )
                }
                item {
                    DifficultySection(
                        selectedStages = selectedStages,
                        onStagesChanged = { selectedStages = it }
                    )
                }
                item {
                    NumberOfCardsSection(
                        totalAvailable = totalItemCount,
                        amount = amount,
                        onAmountChanged = { amount = it },
                        dueTodayOnly = exerciseConfig.dueTodayOnly,
                        onDueTodayOnlyChanged = { updateConfig(exerciseConfig.copy(dueTodayOnly = it)) }
                    )
                }
                item {
                    QuestionTypesSection(
                        selectedTypes = exerciseConfig.selectedExerciseTypes,
                        onTypeSelected = { type ->
                            val current = exerciseConfig.selectedExerciseTypes.toMutableSet()
                            if (type in current) {
                                if (current.size > 1) current.remove(type)
                            } else {
                                current.add(type)
                            }
                            updateConfig(exerciseConfig.copy(selectedExerciseTypes = current))
                        }
                    )
                }
                item { Spacer(modifier = Modifier.height(24.dp)) }
            }

            BottomButtonSection(
                enabled = totalItemCount > 0 && amount > 0,
                amount = amount,
                onStart = {
                    val finalItems = if (exerciseConfig.shuffleCards) {
                        itemsToShow.shuffled().take(amount)
                    } else {
                        itemsToShow.take(amount)
                    }


                    exerciseViewModel.startExerciseWithConfig(
                        finalItems,
                        exerciseConfig.copy(
                            exerciseItemCount = finalItems.size,
                            originalExerciseItems = finalItems,
                            originLanguageId = selectedOriginLanguage?.nameResId,
                            targetLanguageId = selectedTargetLanguage?.nameResId
                        )
                    )

                    @Suppress("HardCodedStringLiteral")
                    navController.navigate("vocabulary_exercise/false")
                }
            )
        }
    }
}

@Composable
fun TopBarSection(
    onBackClick: () -> Unit,
    shuffleCards: Boolean,
    onShuffleCardsChanged: (Boolean) -> Unit,
    shuffleLanguages: Boolean,
    onShuffleLanguagesChanged: (Boolean) -> Unit,
    shuffleLanguagesEnabled: Boolean,
    trainingMode: Boolean,
    onTrainingModeChanged: (Boolean) -> Unit
) {
    var showSettings by remember { mutableStateOf(false) }
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    val scope = rememberCoroutineScope()

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 16.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        IconButton(
            onClick = onBackClick,
            modifier = Modifier
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))
        ) {
            Icon(
                imageVector = Icons.Default.ArrowBackIosNew,
                contentDescription = stringResource(R.string.cd_back),
                modifier = Modifier.size(18.dp),
                tint = MaterialTheme.colorScheme.primary
            )
        }

        Text(
            text = stringResource(R.string.label_start_exercise),
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold,
            modifier = Modifier.weight(1f),
            textAlign = TextAlign.Center
        )

        IconButton(
            onClick = { showSettings = true },
            modifier = Modifier
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f))
        ) {
            Icon(
                imageVector = Icons.Default.Settings,
                contentDescription = stringResource(R.string.cd_settings),
                modifier = Modifier.size(20.dp),
                tint = MaterialTheme.colorScheme.primary
            )
        }
    }

    if (showSettings) {
        StartExerciseSettingsBottomSheet(
            sheetState = sheetState,
            shuffleCards = shuffleCards,
            onShuffleCardsChanged = onShuffleCardsChanged,
            shuffleLanguages = shuffleLanguages,
            onShuffleLanguagesChanged = onShuffleLanguagesChanged,
            shuffleLanguagesEnabled = shuffleLanguagesEnabled,
            trainingMode = trainingMode,
            onTrainingModeChanged = onTrainingModeChanged,
            onDismiss = {
                scope.launch { sheetState.hide() }.invokeOnCompletion {
                    if (!sheetState.isVisible) {
                        @Suppress("AssignedValueIsNeverRead")
                        showSettings = false
                    }
                }
            }
        )
    }
}

@Composable
fun SectionHeader(title: String, actionText: String? = null, onActionClick: () -> Unit = {}) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(bottom = 12.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment = Alignment.CenterVertically
    ) {
        Text(
            text = title.uppercase(),
            style = MaterialTheme.typography.labelMedium,
            fontWeight = FontWeight.Bold,
            letterSpacing = 1.sp,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        if (actionText != null) {
            Text(
                text = actionText,
                style = MaterialTheme.typography.labelMedium,
                color = MaterialTheme.colorScheme.primary,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.clickable { onActionClick() }
            )
        }
    }
}

@Composable
fun LanguagePairSection(
    selectedPairs: List<Pair<Language, Language>>,
    availableLanguageIds: Set<Int>,
    onPairsChanged: (List<Pair<Language, Language>>) -> Unit,
    onOriginLanguageSelected: (Language?) -> Unit,
    onTargetLanguageSelected: (Language?) -> Unit,
    languageSelectionEnabled: Boolean,
    selectedPairsCount: Int,
    selectedOriginLanguage: Language?,
    selectedTargetLanguage: Language?
) {
    val activity = androidx.compose.ui.platform.LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val allLanguages by languageViewModel.allLanguages.collectAsState(initial = emptyList())

    val availableLanguages = remember(availableLanguageIds, allLanguages) {
        allLanguages.filter { it.nameResId in availableLanguageIds }
    }

    val allItems by vocabularyViewModel.vocabularyItems.collectAsState(initial = emptyList())
    val pairCounts = remember(allItems) {
        allItems.mapNotNull { item ->
            val first = item.languageFirstId
            val second = item.languageSecondId
            if (first != null && second != null) {
                val pair = if (first < second) first to second else second to first
                pair
            } else {
                null
            }
        }.groupingBy { it }.eachCount()
    }

    val availablePairs = remember(pairCounts, allLanguages) {
        pairCounts.entries
            .sortedByDescending { it.value }
            .mapNotNull { (pairIds, _) ->
                val first = allLanguages.find { it.nameResId == pairIds.first }
                val second = allLanguages.find { it.nameResId == pairIds.second }
                if (first != null && second != null) first to second else null
            }
    }

    Column {
        SectionHeader(title = stringResource(R.string.language_pair))

        if (availablePairs.isEmpty()) {
            Text(
                text = stringResource(R.string.text_no_dictionary_language_pairs_found),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        } else {
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                availablePairs.forEach { pair ->
                    val isSelected = selectedPairs.contains(pair)
                    LanguageChip(
                        text = "${pair.first.name} ⇄ ${pair.second.name}",
                        isSelected = isSelected,
                        modifier = Modifier.widthIn(min = 160.dp),
                        onClick = {
                            val updated = if (isSelected) {
                                selectedPairs - pair
                            } else {
                                selectedPairs + pair
                            }
                            onPairsChanged(updated)
                        }
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))
        Text(
            text = stringResource(R.string.label_language_direction),
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.Bold
        )
        Text(
            text = stringResource(R.string.text_language_direction_explanation),
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        if (!languageSelectionEnabled && selectedPairsCount > 0) {
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = stringResource(R.string.text_language_direction_disabled_with_pairs),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        Spacer(modifier = Modifier.height(12.dp))
        Row(
            horizontalArrangement = Arrangement.spacedBy(16.dp),
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = stringResource(R.string.label_origin_language),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                eu.gaudian.translator.view.composable.SingleLanguageDropDown(
                    modifier = Modifier.fillMaxWidth(),
                    languageViewModel = languageViewModel,
                    selectedLanguage = selectedOriginLanguage,
                    onLanguageSelected = { language ->
                        if (selectedTargetLanguage?.nameResId == language.nameResId) return@SingleLanguageDropDown
                        onOriginLanguageSelected(language)
                    },
                    showNoneOption = true,
                    onNoneSelected = { onOriginLanguageSelected(null) },
                    alternateLanguages = availableLanguages,
                    restrictToAlternateLanguages = true,
                    enabled = languageSelectionEnabled
                )
            }
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = stringResource(R.string.label_target_language),
                    style = MaterialTheme.typography.bodyMedium,
                    modifier = Modifier.padding(bottom = 8.dp)
                )
                eu.gaudian.translator.view.composable.SingleLanguageDropDown(
                    modifier = Modifier.fillMaxWidth(),
                    languageViewModel = languageViewModel,
                    selectedLanguage = selectedTargetLanguage,
                    onLanguageSelected = { language ->
                        if (selectedOriginLanguage?.nameResId == language.nameResId) return@SingleLanguageDropDown
                        onTargetLanguageSelected(language)
                    },
                    showNoneOption = true,
                    onNoneSelected = { onTargetLanguageSelected(null) },
                    alternateLanguages = availableLanguages,
                    restrictToAlternateLanguages = true,
                    enabled = languageSelectionEnabled
                )
            }
        }
    }
}


@Composable
fun LanguageChip(text: String, isSelected: Boolean, modifier: Modifier = Modifier, onClick: () -> Unit) {
    Surface(
        modifier = modifier.height(56.dp),
        shape = RoundedCornerShape(16.dp),
        color = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.1f) else MaterialTheme.colorScheme.surfaceVariant,
        border = if (isSelected) BorderStroke(2.dp, MaterialTheme.colorScheme.primary) else null,
        onClick = onClick
    ) {
        Row(
            modifier = Modifier.padding(horizontal = 16.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.Center
        ) {
            // Dummy overlapping flags
            Box(modifier = Modifier.width(32.dp)) {
                Box(modifier = Modifier
                    .size(20.dp)
                    .clip(CircleShape)
                    .background(Color.Red)
                    .align(Alignment.CenterStart))
                Box(modifier = Modifier
                    .size(20.dp)
                    .clip(CircleShape)
                    .background(Color.Blue)
                    .align(Alignment.CenterEnd))
            }
            Spacer(modifier = Modifier.width(8.dp))
            Text(text = text, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.bodyMedium)
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun CategoriesSection(
    selectedCategories: List<VocabularyCategory>,
    onCategoriesChanged: (List<VocabularyCategory>) -> Unit
) {
    val activity = androidx.compose.ui.platform.LocalContext.current.findActivity()
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val categories by categoryViewModel.categories.collectAsState(initial = emptyList())

    Column {
        SectionHeader(title = stringResource(R.string.label_categories))

        val tagCategories = categories.filterIsInstance<TagCategory>()
        if (tagCategories.size > 15) {
            CategoryDropdown(
                onCategorySelected = { selections ->
                    onCategoriesChanged(selections.filterNotNull())
                },
                multipleSelectable = true,
                onlyLists = false,
                addCategory = false,
                modifier = Modifier.fillMaxWidth(),
                enableSearch = true
            )
        } else {
            FlowRow(
                horizontalArrangement = Arrangement.spacedBy(8.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp),
                modifier = Modifier.fillMaxWidth()
            ) {
                tagCategories.forEach { category ->
                    val isSelected = selectedCategories.contains(category)
                    Surface(
                        shape = RoundedCornerShape(20.dp),
                        color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
                        onClick = {
                            val updated = if (isSelected) {
                                selectedCategories - category
                            } else {
                                selectedCategories + category
                            }
                            onCategoriesChanged(updated)
                        }
                    ) {
                        Text(
                            text = category.name,
                            color = if (isSelected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
                        )
                    }
                }
            }
        }
    }
}
//Make it a flow row, as all stages in one row does not work
@Composable
fun DifficultySection(
    selectedStages: List<VocabularyStage>,
    onStagesChanged: (List<VocabularyStage>) -> Unit
) {
    val context = androidx.compose.ui.platform.LocalContext.current
    Column {
        SectionHeader(title = stringResource(R.string.label_filter_by_stage))
        FlowRow(
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            VocabularyStage.entries.forEach { stage ->
                val isSelected = selectedStages.contains(stage)
                Surface(
                    shape = RoundedCornerShape(20.dp),
                    color = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant,
                    onClick = {
                        val updated = if (isSelected) {
                            selectedStages - stage
                        } else {
                            selectedStages + stage
                        }
                        onStagesChanged(updated)
                    }
                ) {
                    Text(
                        text = stage.toString(context),
                        color = if (isSelected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp),
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal
                    )
                }
            }
        }
    }
}

@Composable
fun NumberOfCardsSection(
    totalAvailable: Int,
    amount: Int,
    onAmountChanged: (Int) -> Unit,
    dueTodayOnly: Boolean,
    onDueTodayOnlyChanged: (Boolean) -> Unit
) {
    Column {
        OptionItemSwitch(
            title = stringResource(R.string.text_due_today_only),
            description = stringResource(R.string.text_due_today_only_description),
            checked = dueTodayOnly,
            onCheckedChange = onDueTodayOnlyChanged
        )

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

        if (totalAvailable == 0) {
            Text(
                text = stringResource(R.string.no_cards_found_for_the_selected_filters),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.error
            )
            return@Column
        }

        val maxAvailable = totalAvailable.coerceAtLeast(1)
        val coercedAmount = amount.coerceIn(1, maxAvailable)
        if (coercedAmount != amount) {
            onAmountChanged(coercedAmount)
        }

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = stringResource(R.string.text_amount_of_cards).uppercase(),
                style = MaterialTheme.typography.labelMedium,
                fontWeight = FontWeight.Bold,
                letterSpacing = 1.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            Surface(
                shape = RoundedCornerShape(12.dp),
                color = MaterialTheme.colorScheme.primary,
            ) {
                Text(
                    text = "$coercedAmount / $totalAvailable",
                    color = MaterialTheme.colorScheme.onPrimary,
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)
                )
            }
        }

        AppSlider(
            value = coercedAmount.toFloat(),
            onValueChange = { onAmountChanged(it.toInt().coerceIn(1, maxAvailable)) },
            valueRange = 1f..maxAvailable.toFloat(),
            steps = if (maxAvailable > 1) maxAvailable - 2 else 0,
            modifier = Modifier.fillMaxWidth()
        )

        val quickSelectValues = listOf(10, 25, 50, 100)
        val availableQuickSelections = quickSelectValues.filter { it <= maxAvailable }
        if (availableQuickSelections.isNotEmpty()) {
            Spacer(modifier = Modifier.height(12.dp))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                availableQuickSelections.forEach { value ->
                    AppOutlinedButton(
                        onClick = { onAmountChanged(value) },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text(value.toString())
                    }
                }
            }
        }
    }
}
//TODO use our four question types here, from StartScreen.kt, user must select at least one
@Composable
fun QuestionTypesSection(
    selectedTypes: Set<VocabularyExerciseType>,
    onTypeSelected: (VocabularyExerciseType) -> Unit
) {
    Column {
        SectionHeader(title = stringResource(R.string.text_question_types))

        QuestionTypeCard(
            title = stringResource(R.string.label_guessing_exercise),
            subtitle = stringResource(R.string.flip_card),
            icon = AppIcons.Guessing,
            isSelected = selectedTypes.contains(VocabularyExerciseType.GUESSING),
            onClick = { onTypeSelected(VocabularyExerciseType.GUESSING) }
        )
        Spacer(modifier = Modifier.height(12.dp))
        QuestionTypeCard(
            title = stringResource(R.string.label_spelling_exercise),
            subtitle = stringResource(R.string.type_the_translation),
            icon = AppIcons.SpellCheck,
            isSelected = selectedTypes.contains(VocabularyExerciseType.SPELLING),
            onClick = { onTypeSelected(VocabularyExerciseType.SPELLING) }
        )
        Spacer(modifier = Modifier.height(12.dp))
        QuestionTypeCard(
            title = stringResource(R.string.label_multiple_choice_exercise),
            subtitle = stringResource(R.string.label_choose_exercise_types),
            icon = AppIcons.CheckList,
            isSelected = selectedTypes.contains(VocabularyExerciseType.MULTIPLE_CHOICE),
            onClick = { onTypeSelected(VocabularyExerciseType.MULTIPLE_CHOICE) }
        )
        Spacer(modifier = Modifier.height(12.dp))
        QuestionTypeCard(
            title = stringResource(R.string.label_word_jumble_exercise),
            subtitle = stringResource(R.string.text_assemble_the_word_here),
            icon = AppIcons.Extension,
            isSelected = selectedTypes.contains(VocabularyExerciseType.WORD_JUMBLE),
            onClick = { onTypeSelected(VocabularyExerciseType.WORD_JUMBLE) }
        )
    }
}

@Composable
fun QuestionTypeCard(title: String, subtitle: String, icon: ImageVector, isSelected: Boolean, onClick: () -> Unit) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(16.dp),
        color = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.05f) else MaterialTheme.colorScheme.surfaceVariant,
        border = if (isSelected) BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)) else null,
        onClick = onClick
    ) {
        Row(
            modifier = Modifier.padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Box(
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.surface),
                contentAlignment = Alignment.Center
            ) {
                Icon(imageVector = icon, contentDescription = null, tint = MaterialTheme.colorScheme.primary)
            }
            Spacer(modifier = Modifier.width(16.dp))
            Column(modifier = Modifier.weight(1f)) {
                Text(text = title, fontWeight = FontWeight.Bold, style = MaterialTheme.typography.bodyLarge)
                Text(text = subtitle, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            }
            Icon(
                imageVector = if (isSelected) Icons.Default.CheckCircle else Icons.Outlined.Circle,
                contentDescription = null,
                tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}
@Composable
fun BottomButtonSection(
    enabled: Boolean,
    amount: Int,
    onStart: () -> Unit
) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(24.dp)
    ) {
        AppButton(
            onClick = onStart,
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp),
            enabled = enabled,
            shape = RoundedCornerShape(28.dp)
        ) {
            Row(
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = stringResource(R.string.label_start_exercise_2d, amount),
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold
                )
                Spacer(modifier = Modifier.width(8.dp))
                Icon(
                    imageVector = Icons.Default.PlayArrow,
                    contentDescription = stringResource(R.string.cd_play),
                    modifier = Modifier.size(20.dp)
                )
            }
        }
    }
}

@Composable
private fun StartExerciseSettingsBottomSheet(
    sheetState: SheetState,
    shuffleCards: Boolean,
    onShuffleCardsChanged: (Boolean) -> Unit,
    shuffleLanguages: Boolean,
    onShuffleLanguagesChanged: (Boolean) -> Unit,
    shuffleLanguagesEnabled: Boolean,
    trainingMode: Boolean,
    onTrainingModeChanged: (Boolean) -> Unit,
    onDismiss: () -> Unit
) {
    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 20.dp, vertical = 16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Text(
                text = stringResource(R.string.options),
                style = MaterialTheme.typography.titleMedium,
                fontWeight = FontWeight.Bold
            )
            OptionItemSwitch(
                title = stringResource(R.string.shuffle_cards),
                description = stringResource(R.string.text_shuffle_card_order_description),
                checked = shuffleCards,
                onCheckedChange = onShuffleCardsChanged
            )
            OptionItemSwitch(
                title = stringResource(R.string.text_shuffle_languages),
                description = stringResource(R.string.text_shuffle_languages_description),
                checked = shuffleLanguages && shuffleLanguagesEnabled,
                onCheckedChange = { enabled ->
                    if (shuffleLanguagesEnabled) {
                        onShuffleLanguagesChanged(enabled)
                    } else {
                        onShuffleLanguagesChanged(false)
                    }
                }
            )
            if (!shuffleLanguagesEnabled) {
                Text(
                    text = stringResource(R.string.text_shuffle_languages_disabled_by_direction),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
            OptionItemSwitch(
                title = stringResource(R.string.label_training_mode),
                description = stringResource(R.string.text_training_mode_description),
                checked = trainingMode,
                onCheckedChange = onTrainingModeChanged
            )
        }
    }
}