package eu.gaudian.translator.view.dialogs

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.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DividerDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Switch
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.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.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.TagCategory
import eu.gaudian.translator.model.VocabularyFilter
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.AppIcons
import eu.gaudian.translator.view.composable.AppOutlinedTextField
import eu.gaudian.translator.view.composable.MultipleLanguageDropdown
import eu.gaudian.translator.view.hints.HintDefinition
import eu.gaudian.translator.viewmodel.CategoryViewModel
import eu.gaudian.translator.viewmodel.LanguageViewModel


enum class DialogCategoryType { TAG, FILTER }

@Composable
fun AddCategoryDialog(
    onDismiss: () -> Unit
) {
    val activity = LocalContext.current.findActivity()
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    var categoryName by remember { mutableStateOf("") }
    var selectedLanguages by remember { mutableStateOf<List<Language>>(emptyList()) }
    var selectedStages by remember { mutableStateOf<List<VocabularyStage?>>(emptyList()) }
    var selectedTab by remember { mutableStateOf(DialogCategoryType.TAG) }
    var selectedDictionaryPair by remember { mutableStateOf<Pair<Int, Int>?>(null) }

    val categoryTypes = DialogCategoryType.entries.map {
        when (it) {
            DialogCategoryType.TAG -> stringResource(R.string.text_list)
            DialogCategoryType.FILTER -> stringResource(R.string.text_filter)
        }
    }

    val isConfirmEnabled = categoryName.isNotBlank()

    AppDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(R.string.label_add_category)) },
        hintContent = HintDefinition.CATEGORY.hint(),
        content = {
            Column(modifier = Modifier.fillMaxWidth()) {
                SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
                    categoryTypes.forEachIndexed { index, label ->
                        SegmentedButton(
                            shape = SegmentedButtonDefaults.itemShape(index = index, count = categoryTypes.size),
                            onClick = { selectedTab = DialogCategoryType.entries[index] },
                            selected = index == selectedTab.ordinal
                        ) {
                            Text(label)
                        }
                    }
                }

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

                AppOutlinedTextField(
                    value = categoryName,
                    onValueChange = { categoryName = it },
                    label = { Text(stringResource(R.string.text_category_name)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                )

                if (selectedTab == DialogCategoryType.FILTER) {
                    Spacer(modifier = Modifier.height(16.dp))

                    var isLanguageFilterEnabled by remember { mutableStateOf(false) }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = stringResource(R.string.language_filter))
                        Switch(
                            checked = isLanguageFilterEnabled,
                            onCheckedChange = {
                                isLanguageFilterEnabled = it
                                if (!it) { // Reset on disable
                                    selectedLanguages = emptyList()
                                    selectedDictionaryPair = null
                                }
                            }
                        )
                    }

                    // **Conditional Language Filter Options**
                    if (isLanguageFilterEnabled) {
                        Spacer(modifier = Modifier.height(8.dp))
                        var languageFilterType by remember { mutableIntStateOf(0) } // 0=Languages, 1=Dictionary
                        val filterOptions = listOf(
                            stringResource(R.string.label_languages),
                            stringResource(R.string.language_pair)
                        )
                        SingleChoiceSegmentedButtonRow(modifier = Modifier.fillMaxWidth()) {
                            filterOptions.forEachIndexed { index, label ->
                                SegmentedButton(
                                    shape = SegmentedButtonDefaults.itemShape(index = index, count = filterOptions.size),
                                    onClick = {
                                        languageFilterType = index
                                        // Reset other option's selection when switching
                                        if (languageFilterType == 0) selectedDictionaryPair = null
                                        if (languageFilterType == 1) selectedLanguages = emptyList()
                                    },
                                    selected = index == languageFilterType,
                                ) { Text(label) }
                            }
                        }

                        if (languageFilterType == 0) { // Languages
                            MultipleLanguageDropdown(
                                languageViewModel = languageViewModel,
                                modifier = Modifier.fillMaxWidth(),
                                onLanguagesSelected = { languages ->
                                    selectedLanguages = languages
                                },
                            )
                        } else { // Dictionary
                            DictionarySelectionContent(
                                selectedPair = selectedDictionaryPair,
                                onPairSelected = { selectedDictionaryPair = it }
                            )
                        }
                    }

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

                    // **Stage Filter Switch**
                    var isStageFilterEnabled by remember { mutableStateOf(false) }
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(text = stringResource(R.string.stage_filter))
                        Switch(
                            checked = isStageFilterEnabled,
                            onCheckedChange = {
                                isStageFilterEnabled = it
                                if (!it) { // Reset on disable
                                    selectedStages = emptyList()
                                }
                            }
                        )
                    }

                    // **Conditional Stage Filter Options**
                    if (isStageFilterEnabled) {
                        VocabularyStageDropDown(
                            onStageSelected = { stages ->
                                selectedStages = stages.filterNotNull()
                            },
                            modifier = Modifier.fillMaxWidth(),
                            multipleSelectable = true,
                            preselectedStages = emptyList(),
                            noneSelectable = true
                        )
                    }
                }

                if (selectedTab == DialogCategoryType.TAG) {
                    Spacer(modifier = Modifier.height(8.dp))
                    Text(text = stringResource(R.string.text_a_simple_list_to))
                }

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.End
                ) {
                    TextButton(onClick = onDismiss) {
                        Text(stringResource(R.string.label_cancel))
                    }
                    Spacer(modifier = Modifier.widthIn(8.dp))
                    TextButton(
                        enabled = isConfirmEnabled,
                        onClick = {
                            when (selectedTab) {
                                DialogCategoryType.TAG -> {
                                    val newList = TagCategory(id = 0, name = categoryName.trim())
                                    categoryViewModel.createCategory(newList)
                                }

                                DialogCategoryType.FILTER -> {
                                    val newFilter = VocabularyFilter(
                                        id = 0,
                                        name = categoryName.trim(),
                                        languages = if (selectedDictionaryPair == null) selectedLanguages.map { it.nameResId }
                                            .ifEmpty { null } else null,
                                        languagePairs = selectedDictionaryPair,
                                        stages = selectedStages.filterNotNull().ifEmpty { null }
                                    )
                                    categoryViewModel.createCategory(newFilter)
                                }
                            }
                            onDismiss()
                        }
                    ) {
                        Text(stringResource(R.string.label_add))
                    }
                }
            }
        }
    )
}

@Composable
private fun DictionarySelectionContent(
    selectedPair: Pair<Int, Int>?,
    onPairSelected: (Pair<Int, Int>) -> Unit
) {
    val activity = LocalContext.current.findActivity()
    val categoryViewModel: CategoryViewModel = hiltViewModel(viewModelStoreOwner = activity)
    val languageViewModel: LanguageViewModel = hiltViewModel(viewModelStoreOwner = activity)
    var allDictionaries by remember { mutableStateOf<List<Pair<Language, Language>>>(emptyList()) }
    var isLoading by remember { mutableStateOf(true) }
    val allCategories by categoryViewModel.categories.collectAsState()

    LaunchedEffect(allCategories) {
        isLoading = true
        val existingIdPairs = allCategories.filterIsInstance<VocabularyFilter>().mapNotNull { it.languagePairs }
        val possibleIdPairs = categoryViewModel.calculateNewDictionaries()

        // Unify existing and possible pairs into a single set to remove duplicates
        val allUniqueIdPairs = (possibleIdPairs.toSet() + existingIdPairs.toSet()).toList()

        @Suppress("HardCodedStringLiteral")
        suspend fun resolveLanguage(id: Int): Language? = languageViewModel.getLanguageById(id).takeIf { it.code != "error" }

        val resolvedPairs = mutableListOf<Pair<Language, Language>>()
        for ((id1, id2) in allUniqueIdPairs) {
            val lang1 = resolveLanguage(id1)
            val lang2 = resolveLanguage(id2)
            if (lang1 != null && lang2 != null) {
                resolvedPairs.add(lang1 to lang2)
            }
        }

        // Sort alphabetically for consistent ordering
        allDictionaries = resolvedPairs.sortedBy { it.first.name + " - " + it.second.name }
        isLoading = false
    }

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

    when {
        isLoading -> {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp), contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }
        allDictionaries.isEmpty() -> {
            Text(
                text = stringResource(R.string.text_no_dictionary_language_pairs_found),
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(top = 8.dp)
            )
        }
        else -> {
            LazyColumn(modifier = Modifier.heightIn(max = 200.dp)) {
                item {
                    Text(
                        text = stringResource(R.string.text_available_to_create_2d),
                        style = MaterialTheme.typography.labelLarge,
                        modifier = Modifier.padding(vertical = 8.dp)
                    )
                    HorizontalDivider(Modifier, DividerDefaults.Thickness, DividerDefaults.color)
                }
                items(allDictionaries) { (lang1, lang2) ->
                    val currentPairIds = Pair(lang1.nameResId, lang2.nameResId)
                    DictionaryRow(
                        lang1 = lang1,
                        lang2 = lang2,
                        isSelected = selectedPair == currentPairIds,
                        onClick = { onPairSelected(currentPairIds) },
                        enabled = true // All rows are always enabled
                    )
                }
            }
        }
    }
}

@androidx.compose.ui.tooling.preview.Preview
@Composable
fun AddCategoryDialogPreview() {
    AddCategoryDialog(
        onDismiss = {}
    )
}

@androidx.compose.ui.tooling.preview.Preview
@Composable
fun DictionarySelectionContentPreview() {
    LocalContext.current
    DictionarySelectionContent(
        selectedPair = Pair(R.string.language_1, R.string.language_2),
        onPairSelected = {}
    )
}

@Suppress("HardCodedStringLiteral")
@androidx.compose.ui.tooling.preview.Preview
@Composable
fun DictionaryRowPreview() {
    DictionaryRow(
        lang1 = Language(
            code = "en",
            region = "US",
            nameResId = R.string.language_1,
            name = "English",
            englishName =  "English",
            isCustom = false,
            isSelected = false
        ),
        lang2 = Language(
            code = "es",
            region = "ES",
            nameResId = R.string.language_2,
            name = "Spanish",
            englishName =  "Spanish",
            isCustom = false,
            isSelected = false
        ),
        isSelected = true,
        enabled = false,
        onClick = {}
    )
}

@Composable
private fun DictionaryRow(
    lang1: Language,
    lang2: Language,
    isSelected: Boolean,
    enabled: Boolean = true,
    onClick: () -> Unit = {}
) {
    val textColor = when {
        !enabled -> MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
        else -> MaterialTheme.colorScheme.onSurface
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(enabled = enabled, onClick = onClick)
            .padding(vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = "${lang1.name} - ${lang2.name}",
            style = MaterialTheme.typography.bodyMedium,
            color = textColor
        )
        if (isSelected) {
            Icon(
                imageVector = AppIcons.Check,
                contentDescription = stringResource(R.string.text_selected),
                tint = MaterialTheme.colorScheme.primary
            )
        }
    }
}
