package eu.gaudian.translator.view.vocabulary

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.BorderStroke
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.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.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
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.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import eu.gaudian.translator.R
import eu.gaudian.translator.model.CardSet
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.model.VocabularyItem
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.AppScaffold
import eu.gaudian.translator.view.composable.AppSlider
import eu.gaudian.translator.view.composable.AppTopAppBar
import eu.gaudian.translator.view.composable.OptionItemSwitch
import eu.gaudian.translator.view.composable.SingleLanguageDropDown
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel

@Composable
fun StartScreen(
    cardSet: CardSet?,
    onStartClicked: (List<VocabularyItem>) -> Unit,
    onClose: () -> Unit,
    shuffleCards: Boolean,
    onShuffleCardsChanged: (Boolean) -> Unit,
    shuffleLanguages: Boolean,
    onShuffleLanguagesChanged: (Boolean) -> Unit,
    trainingMode: Boolean,
    onTrainingModeChanged: (Boolean) -> Unit,
    dueTodayOnly: Boolean,
    onDueTodayOnlyChanged: (Boolean) -> Unit,
    selectedExerciseTypes: Set<VocabularyExerciseType>,
    onExerciseTypeSelected: (VocabularyExerciseType) -> Unit,
    hideTodayOnlySwitch: Boolean = false,
    selectedOriginLanguage: Language?,
    onOriginLanguageChanged: (Language?) -> Unit,
    selectedTargetLanguage: Language?,
    onTargetLanguageChanged: (Language?) -> Unit,
) {

    val activity = LocalContext.current.findActivity()
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val dueTodayItems by vocabularyViewModel.dueTodayItems.collectAsState(initial = emptyList())
    val allItems = cardSet?.cards ?: emptyList()

    var amount by remember(allItems) { mutableIntStateOf(allItems.size) }

    val itemsToShow = if (dueTodayOnly) {
        allItems.filter { card -> dueTodayItems.any { it.id == card.id } }
    } else {
        allItems
    }

    if (amount > itemsToShow.size) {
        amount = itemsToShow.size
    }

    StartScreenContent(
        vocabularyItemsCount = itemsToShow.size,
        shuffleCards = shuffleCards,
        onShuffleCardsChanged = onShuffleCardsChanged,
        shuffleLanguages = shuffleLanguages,
        onShuffleLanguagesChanged = onShuffleLanguagesChanged,
        trainingMode = trainingMode,
        onTrainingModeChanged = onTrainingModeChanged,
        dueTodayOnly = dueTodayOnly,
        onDueTodayOnlyChanged = onDueTodayOnlyChanged,
        amount = amount,
        onAmountChanged = {
            @Suppress("AssignedValueIsNeverRead")
            amount = it
        },
        onStartClicked = {
            val finalItems = if (shuffleCards) {
                itemsToShow.shuffled().take(amount)
            } else {
                itemsToShow.take(amount)
            }
            onStartClicked(finalItems)
        },
        onClose = onClose,
        selectedExerciseTypes = selectedExerciseTypes,
        onExerciseTypeSelected = onExerciseTypeSelected,
        hideTodayOnlySwitch = hideTodayOnlySwitch,
        selectedOriginLanguage = selectedOriginLanguage,
        onOriginLanguageChanged = onOriginLanguageChanged,
        selectedTargetLanguage = selectedTargetLanguage,
        onTargetLanguageChanged = onTargetLanguageChanged,
        allItems = allItems
    )
}

@Composable
private fun StartScreenContent(
    vocabularyItemsCount: Int,
    shuffleCards: Boolean,
    onShuffleCardsChanged: (Boolean) -> Unit,
    shuffleLanguages: Boolean,
    onShuffleLanguagesChanged: (Boolean) -> Unit,
    trainingMode: Boolean,
    onTrainingModeChanged: (Boolean) -> Unit,
    dueTodayOnly: Boolean,
    onDueTodayOnlyChanged: (Boolean) -> Unit,
    amount: Int,
    onAmountChanged: (Int) -> Unit,
    onStartClicked: () -> Unit,
    onClose: () -> Unit,
    selectedExerciseTypes: Set<VocabularyExerciseType>,
    onExerciseTypeSelected: (VocabularyExerciseType) -> Unit,
    hideTodayOnlySwitch: Boolean = false,
    selectedOriginLanguage: Language?,
    onOriginLanguageChanged: (Language?) -> Unit,
    selectedTargetLanguage: Language?,
    onTargetLanguageChanged: (Language?) -> Unit,
    allItems: List<VocabularyItem>,
) {
    AppScaffold(
        topBar = {
            AppTopAppBar(
                title = { Text(stringResource(R.string.prepare_exercise)) },
                navigationIcon = {
                    IconButton(onClick = onClose) {
                        Icon(
                            AppIcons.Close,
                            contentDescription = stringResource(R.string.label_close)
                        )
                    }
                }
            )
        },

        ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            Box(
                modifier = Modifier.weight(1f)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .verticalScroll(rememberScrollState())
                        .padding(horizontal = 16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Spacer(Modifier.height(16.dp))
                    if (vocabularyItemsCount > 0) {
                        Text(stringResource(R.string.number_of_cards, amount, vocabularyItemsCount))
                        AppSlider(
                            value = amount.toFloat(),
                            onValueChange = { onAmountChanged(it.toInt()) },
                            valueRange = 1f..vocabularyItemsCount.toFloat(),
                            steps = if (vocabularyItemsCount > 1) vocabularyItemsCount - 2 else 0
                        )

                        // Quick selection buttons
                        val quickSelectValues = listOf(10, 25, 50, 100)
                        val availableValues =
                            quickSelectValues.filter { it <= vocabularyItemsCount }

                        if (availableValues.isNotEmpty()) {
                            Spacer(Modifier.height(16.dp))
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.spacedBy(
                                    8.dp,
                                    Alignment.CenterHorizontally
                                )
                            ) {
                                availableValues.forEach { value ->
                                    AppOutlinedButton(
                                        onClick = { onAmountChanged(value) },
                                        modifier = Modifier.weight(1f),
                                        enabled = value <= vocabularyItemsCount
                                    ) {
                                        Text(value.toString())
                                    }
                                }
                            }
                        }
                    } else {
                        Text(
                            stringResource(R.string.no_cards_found_for_the_selected_filters),
                            style = MaterialTheme.typography.bodyLarge,
                            color = MaterialTheme.colorScheme.error
                        )
                    }

                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 24.dp),
                        thickness = DividerDefaults.Thickness,
                        color = DividerDefaults.color
                    )


// Language Selection Section
                    Text(
                        stringResource(R.string.label_language_direction),
                        style = MaterialTheme.typography.titleLarge
                    )

                    Text(
                        stringResource(R.string.text_language_direction_explanation),
                        style = MaterialTheme.typography.bodyMedium
                    )
                    Spacer(Modifier.height(16.dp))

                    val activity = LocalContext.current.findActivity()
                    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)

// Get available languages from the card set
                    val availableLanguages = remember(allItems) {
                        allItems.flatMap { listOfNotNull(it.languageFirstId, it.languageSecondId) }
                            .distinct()
                            .mapNotNull { languageId ->
                                languageViewModel.allLanguages.value.find { it.nameResId == languageId }
                            }
                    }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(16.dp)
                    ) {
                        // Origin Language Dropdown
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                stringResource(R.string.label_origin_language),
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                            SingleLanguageDropDown(
                                modifier = Modifier.fillMaxWidth(),
                                languageViewModel = languageViewModel,
                                selectedLanguage = selectedOriginLanguage,
                                onLanguageSelected = { language ->
                                    onOriginLanguageChanged(language)
                                    // Clear target language if it's the same as origin
                                    if (selectedTargetLanguage?.nameResId == language.nameResId) {
                                        onTargetLanguageChanged(null)
                                    }
                                },
                                showNoneOption = true,
                                alternateLanguages = availableLanguages
                            )
                        }

                        // Target Language Dropdown
                        Column(modifier = Modifier.weight(1f)) {
                            Text(
                                stringResource(R.string.label_target_language),
                                style = MaterialTheme.typography.bodyMedium,
                                modifier = Modifier.padding(bottom = 8.dp)
                            )
                            SingleLanguageDropDown(
                                modifier = Modifier.fillMaxWidth(),
                                languageViewModel = languageViewModel,
                                selectedLanguage = selectedTargetLanguage,
                                onLanguageSelected = { language ->
                                    onTargetLanguageChanged(language)
                                    // Clear origin language if it's the same as target
                                    if (selectedOriginLanguage?.nameResId == language.nameResId) {
                                        onOriginLanguageChanged(null)
                                    }
                                },
                                alternateLanguages = availableLanguages,
                                showNoneOption = true,
                            )
                        }
                    }
                    Spacer(Modifier.height(16.dp))
                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 24.dp),
                        thickness = DividerDefaults.Thickness,
                        color = DividerDefaults.color
                    )

                    Text(
                        stringResource(R.string.label_choose_exercise_types),
                        style = MaterialTheme.typography.titleLarge
                    )
                    Spacer(Modifier.height(16.dp))
                    ExerciseTypeSelector(
                        selectedTypes = selectedExerciseTypes,
                        onTypeSelected = onExerciseTypeSelected
                    )
                    HorizontalDivider(
                        modifier = Modifier.padding(vertical = 24.dp),
                        thickness = DividerDefaults.Thickness,
                        color = DividerDefaults.color
                    )

                    Text(
                        stringResource(R.string.options),
                        style = MaterialTheme.typography.titleLarge
                    )
                    Spacer(Modifier.height(16.dp))

                    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        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,
                            onCheckedChange = onShuffleLanguagesChanged
                        )
                        OptionItemSwitch(
                            title = stringResource(R.string.label_training_mode),
                            description = stringResource(R.string.text_training_mode_description),
                            checked = trainingMode,
                            onCheckedChange = onTrainingModeChanged
                        )
                        if (!hideTodayOnlySwitch) {
                            OptionItemSwitch(
                                title = stringResource(R.string.text_due_today_only),
                                description = stringResource(R.string.text_due_today_only_description),
                                checked = dueTodayOnly,
                                onCheckedChange = onDueTodayOnlyChanged
                            )
                        }
                    }
                    Spacer(Modifier.height(16.dp))
                }
            }
            AppButton(
                onClick = onStartClicked,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .height(50.dp),
                enabled = vocabularyItemsCount > 0 && amount > 0
            ) {
                Text(stringResource(R.string.label_start_exercise_2d, amount))
            }
        }

    }


}

@Composable
private fun ExerciseTypeSelector(
    selectedTypes: Set<VocabularyExerciseType>,
    onTypeSelected: (VocabularyExerciseType) -> Unit,
) {
    // Using FlowRow for a more flexible layout that wraps to the next line if needed
    FlowRow(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(12.dp, Alignment.CenterHorizontally),
        verticalArrangement = Arrangement.spacedBy(12.dp)
    ) {
        ExerciseTypeCard(
            icon = AppIcons.Guessing,
            isSelected = VocabularyExerciseType.GUESSING in selectedTypes,
            onClick = { onTypeSelected(VocabularyExerciseType.GUESSING) },
            text = stringResource(R.string.label_guessing_exercise),
        )
        ExerciseTypeCard(
            icon = AppIcons.SpellCheck,
            isSelected = VocabularyExerciseType.SPELLING in selectedTypes,
            onClick = { onTypeSelected(VocabularyExerciseType.SPELLING) },
            text = stringResource(R.string.label_spelling_exercise),
        )
        ExerciseTypeCard(
            icon = AppIcons.CheckList,
            isSelected = VocabularyExerciseType.MULTIPLE_CHOICE in selectedTypes,
            onClick = { onTypeSelected(VocabularyExerciseType.MULTIPLE_CHOICE) },
            text = stringResource(R.string.label_multiple_choice_exercise),
        )
        ExerciseTypeCard(
            icon = AppIcons.Extension,
            isSelected = VocabularyExerciseType.WORD_JUMBLE in selectedTypes,
            onClick = { onTypeSelected(VocabularyExerciseType.WORD_JUMBLE) },
            text = stringResource(R.string.label_word_jumble_exercise),
        )
    }
}

@Composable
private fun ExerciseTypeCard(
    text: String,
    icon: ImageVector,
    isSelected: Boolean,
    onClick: () -> Unit,
) {
    val borderColor by animateColorAsState(
        targetValue = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(
            alpha = 0.5f
        ),
        label = "borderColorAnimation",
        animationSpec = tween(300)
    )
    val containerColor by animateColorAsState(
        targetValue = if (isSelected) MaterialTheme.colorScheme.primaryContainer else MaterialTheme.colorScheme.surfaceVariant,
        animationSpec = tween(300)
    )

    Card(
        onClick = onClick,
        modifier = Modifier.size(width = 120.dp, height = 100.dp), // Made the cards smaller
        shape = RoundedCornerShape(12.dp),
        border = BorderStroke(2.dp, borderColor),
        colors = CardDefaults.cardColors(containerColor = containerColor),
        elevation = CardDefaults.cardElevation(if (isSelected) 4.dp else 1.dp)
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Icon(icon, contentDescription = null, modifier = Modifier.size(32.dp)) // Smaller icon
            Spacer(Modifier.height(8.dp))
            Text(
                text = text,
                style = MaterialTheme.typography.bodyLarge, // Smaller text
                fontWeight = FontWeight.Bold,
                textAlign = TextAlign.Center
            )
        }
    }
}