package eu.gaudian.translator.view.dialogs

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
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.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.Language
import eu.gaudian.translator.model.VocabularyCategory
import eu.gaudian.translator.model.VocabularyStage
import eu.gaudian.translator.utils.findActivity
import eu.gaudian.translator.view.composable.AppDialog
import eu.gaudian.translator.view.composable.MultipleLanguageDropdown
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel
import eu.gaudian.translator.viewmodel.VocabularyViewModel
import kotlinx.coroutines.launch

@Composable
fun StartExerciseDialog(
    onDismiss: () -> Unit,
    onConfirm: (
        categories: List<VocabularyCategory>,
        stages: List<VocabularyStage>,
        languageIds: List<Int>
    ) -> Unit
) {
    val activity = LocalContext.current.findActivity()
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val vocabularyViewModel: VocabularyViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    
    val coroutineScope = rememberCoroutineScope()
    val categories by categoryViewModel.categories.collectAsState(initial = emptyList())
    
    var lids by remember { mutableStateOf<List<Int>>(emptyList()) }
    var languages by remember { mutableStateOf<List<Language>>(emptyList()) }
    // Map displayed Language to its DB id (lid) using position mapping from load
    var languageIdMap by remember { mutableStateOf<Map<Language, Int>>(emptyMap()) }
    var selectedLanguages by remember { mutableStateOf<List<Language>>(emptyList()) }
    var selectedStages by remember { mutableStateOf<List<VocabularyStage>>(emptyList()) }
    var selectedCategories by remember { mutableStateOf<List<VocabularyCategory>>(emptyList()) }

    LaunchedEffect(Unit) {
        coroutineScope.launch {
            lids = vocabularyViewModel.getAllLanguagesIdsPresent().filterNotNull().toList()
            languages = lids.map { lid ->
                languageViewModel.getLanguageById(lid)
            }
            // build reverse map
            languageIdMap = languages.mapIndexed { index, lang -> lang to lids.getOrNull(index) }.filter { it.second != null }.associate { it.first to it.second!! }
        }
    }

    AppDialog(onDismissRequest = onDismiss, title = { Text(stringResource(R.string.label_start_exercise)) }) {

        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            MultipleLanguageDropdown(
                modifier = Modifier.fillMaxWidth(),
                languageViewModel = languageViewModel,
                onLanguagesSelected = { langs ->
                    selectedLanguages = langs
                },
                languages
            )
            CategoryDropdown(
                onCategorySelected = { cats ->
                    selectedCategories = cats.filterIsInstance<VocabularyCategory>()
                },
                multipleSelectable = true,
                onlyLists = false, // Show both filters and lists
                addCategory = false,
                modifier = Modifier.fillMaxWidth(),
            )
            VocabularyStageDropDown(
                modifier = Modifier.fillMaxWidth(),
                preselectedStages = selectedStages,
                onStageSelected = { stages ->
                    @Suppress("FilterIsInstanceResultIsAlwaysEmpty")
                    selectedStages = stages.filterIsInstance<VocabularyStage>()
                },
                multipleSelectable = true
            )

            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(top = 16.dp),
                horizontalArrangement = Arrangement.End
            ) {
                TextButton(
                    onClick = onDismiss,
                ) {
                    Text(stringResource(R.string.label_cancel))
                }
                TextButton(
                    onClick = {
                        run {
                            val ids = selectedLanguages.mapNotNull { languageIdMap[it] }
                            onConfirm(selectedCategories, selectedStages, ids)
                        }
                    }
                ) {
                    Text(stringResource(R.string.label_start_exercise))
                }
            }
        }
    }
}
