@file:Suppress("AssignedValueIsNeverRead", "HardCodedStringLiteral")

package eu.gaudian.translator.view.composable

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.ModalBottomSheet
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.Language
import eu.gaudian.translator.viewmodel.LanguageViewModel


@Composable
fun BaseLanguageDropDown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel,
    selectedLanguage: Language?,
    onLanguageSelected: (Language) -> Unit,
    showAutoOption: Boolean = false,
    onAutoSelected: () -> Unit = {},
    showNoneOption: Boolean = false,
    onNoneSelected: () -> Unit = {},
    enableMultipleSelection: Boolean = false,
    onLanguagesSelected: (List<Language>) -> Unit = {},
    alternateLanguages: List<Language> = emptyList(),
    restrictToAlternateLanguages: Boolean = false,
    enabled: Boolean = true,
    iconEnabled: Boolean = true,
    noBorder: Boolean = false,
) {
    val defaultLanguages by languageViewModel.allLanguages.collectAsState(initial = emptyList())
    val favoriteLanguages by languageViewModel.favoriteLanguages.collectAsState()
    val languageHistory by languageViewModel.languageHistory.collectAsState()

    var expanded by remember { mutableStateOf(false) }
    var searchText by remember { mutableStateOf("") }
    var tempSelection by remember { mutableStateOf<List<Language>>(emptyList()) }
    var selectedLanguagesCount by remember { mutableIntStateOf(if (enableMultipleSelection) tempSelection.size else 0) }

    val languages = remember(alternateLanguages, defaultLanguages, restrictToAlternateLanguages) {
        if (restrictToAlternateLanguages) {
            alternateLanguages
        } else {
            alternateLanguages.ifEmpty { defaultLanguages }
        }
    }

    val buttonText = when {
        enableMultipleSelection && selectedLanguagesCount > 0 -> stringResource(
            R.string.text_2d_languages_selected,
            selectedLanguagesCount
        )
        enableMultipleSelection && selectedLanguagesCount == 0 -> stringResource(R.string.text_select_languages)
        selectedLanguage != null -> selectedLanguage.name
        showAutoOption -> stringResource(R.string.label_language_auto)
        else -> stringResource(R.string.label_language_none)
    }

    Box(
        modifier = modifier.fillMaxWidth(),
        contentAlignment = Alignment.TopCenter
    ) {
        AppOutlinedButton(
            shape = RoundedCornerShape(8.dp),
            onClick = { expanded = true },
            enabled = enabled,
            contentPadding = if (!iconEnabled) PaddingValues(0.dp) else PaddingValues(horizontal = 16.dp, vertical = 8.dp),
            borderColor = if (noBorder) Color.Unspecified else null
        ) {
            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = buttonText,
                    modifier = Modifier.weight(1f),
                    textAlign = TextAlign.Center,
                    maxLines = 1
                )
                if (iconEnabled)
                    Icon(
                        imageVector = if (expanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                        contentDescription = if (expanded) stringResource(R.string.cd_collapse) else stringResource(R.string.cd_expand)
                    )
            }
        }

        if (expanded) {
            val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)

            ModalBottomSheet(
                onDismissRequest = {
                    expanded = false
                    searchText = ""
                    tempSelection = emptyList()
                },
                sheetState = sheetState
            ) {
                @Composable
                fun MultiSelectItem(language: Language) {
                    val isSelected = tempSelection.contains(language)
                    AppDropdownMenuItem(
                        text = {
                            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {
                                AppCheckbox(
                                    checked = isSelected,
                                    onCheckedChange = {
                                        tempSelection = if (isSelected) tempSelection - language else tempSelection + language
                                        selectedLanguagesCount = tempSelection.size
                                        onLanguagesSelected(tempSelection)
                                    }
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Text(language.name)
                                if (language.nativeName != language.name) {
                                    Spacer(modifier = Modifier.width(4.dp))
                                    Text(
                                        text = "(${language.nativeName})",
                                        style = TextStyle(
                                            fontStyle = FontStyle.Italic,
                                            fontFamily = FontFamily.Default
                                        )
                                    )
                                }
                            }
                        },
                        onClick = {
                            tempSelection = if (isSelected) tempSelection - language else tempSelection + language
                            selectedLanguagesCount = tempSelection.size
                        }
                    )
                }

                @Composable
                fun SingleSelectItem(language: Language) {
                    val languageNames = languages.map { it.name }
                    val duplicateNames = languageNames.groupingBy { it }.eachCount().filter { it.value > 1 }.keys
                    val isDuplicate = duplicateNames.contains(language.name)

                    AppDropdownMenuItem(
                        text = {
                            Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
                                Column {
                                    Text(text = language.name)
                                    if (language.nativeName != language.name) {
                                        Text(
                                            text = language.nativeName,
                                            style = TextStyle(
                                                fontStyle = FontStyle.Italic,
                                                fontSize = 12.sp,
                                                fontFamily = FontFamily.Default
                                            )
                                        )
                                    }
                                }
                                if (isDuplicate) {
                                    Spacer(modifier = Modifier.width(4.dp))
                                    Text(text = "(${language.region})")
                                }
                                Spacer(modifier = Modifier.weight(1f))
                                IconButton(onClick = {
                                    val isCurrentlyFavorite = favoriteLanguages.contains(language)
                                    val updatedFavorites = if (!isCurrentlyFavorite) favoriteLanguages + language else favoriteLanguages - language
                                    languageViewModel.updateFavoriteLanguages(updatedFavorites)
                                }) {
                                    Icon(
                                        imageVector = if (favoriteLanguages.contains(language)) AppIcons.Favorite else AppIcons.FavoriteOutline,
                                        contentDescription = if (favoriteLanguages.contains(language)) stringResource(
                                            R.string.text_remove_from_favorites
                                        ) else stringResource(R.string.text_add_to_favorites)
                                    )
                                }
                            }
                        },
                        onClick = {
                            onLanguageSelected(language)
                            expanded = false
                            searchText = ""
                        }
                    )
                }

                Column(
                    modifier = Modifier.fillMaxWidth()
                ) {
                    DropdownSearchField(
                        searchQuery = searchText,
                        onSearchQueryChange = { searchText = it },
                        placeholder = { Text(stringResource(R.string.text_search_3d)) },
                    )
                    HorizontalDivider()

                    // Replaced height(max = 900.dp) with standard weight logic to allow proper scrolling bounds
                    Column(
                        modifier = Modifier
                            .weight(1f, fill = false)
                            .verticalScroll(rememberScrollState())
                    ) {
                        val isSearching = searchText.isNotBlank()

                    if (isSearching) {
                        val searchBase = if (restrictToAlternateLanguages) {
                            alternateLanguages
                        } else {
                            favoriteLanguages + languageHistory + languages
                        }
                        val searchResults = searchBase
                                .distinctBy { it.nameResId }
                                .filter { language ->
                                    val matchesName = language.name.contains(searchText, ignoreCase = true)
                                    val matchesNativeName = language.nativeName.contains(searchText, ignoreCase = true)
                                    matchesName || matchesNativeName
                                }
                                .sortedBy { it.name }

                            if (enableMultipleSelection) {
                                searchResults.forEach { language -> MultiSelectItem(language) }
                            } else {
                                searchResults.forEach { language -> SingleSelectItem(language) }
                            }

                    } else if (restrictToAlternateLanguages) {
                        val sortedAlternate = alternateLanguages.sortedBy { it.name }
                        if (enableMultipleSelection) {
                            DropdownHeader(text = stringResource(R.string.text_all_languages))
                            sortedAlternate.forEach { language -> MultiSelectItem(language) }
                        } else {
                            DropdownHeader(text = stringResource(R.string.text_all_languages))
                            sortedAlternate.forEach { language -> SingleSelectItem(language) }
                        }

                    } else if (alternateLanguages.isNotEmpty()) {
                        val sortedAlternate = alternateLanguages.sortedBy { it.name }
                            if (enableMultipleSelection) {
                                DropdownHeader(text = stringResource(R.string.text_all_languages))
                                sortedAlternate.forEach { language -> MultiSelectItem(language) }
                            } else {
                                DropdownHeader(text = stringResource(R.string.text_all_languages))
                                sortedAlternate.forEach { language -> SingleSelectItem(language) }
                            }

                        } else {
                            if (enableMultipleSelection) {
                                if (favoriteLanguages.isNotEmpty()) {
                                    DropdownHeader(text = stringResource(R.string.text_favorites))
                                    favoriteLanguages.forEach { language -> MultiSelectItem(language) }
                                    HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
                                }
                                val recentHistoryFiltered = languageHistory.filter { it !in favoriteLanguages }.takeLast(5)
                                if (recentHistoryFiltered.isNotEmpty() && alternateLanguages.isEmpty()) {
                                    DropdownHeader(text = stringResource(R.string.text_recent_history))
                                    recentHistoryFiltered.forEach { language -> MultiSelectItem(language) }
                                    HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
                                }
                                val remainingLanguages = languages.sortedBy { it.name }
                                if (remainingLanguages.isNotEmpty()) {
                                    DropdownHeader(text = stringResource(R.string.text_all_languages))
                                    remainingLanguages.forEach { language -> MultiSelectItem(language) }
                                }
                            } else {
                                if (showAutoOption) {
                                    LargeDropdownMenuItem(
                                        text = stringResource(R.string.text_select_auto_recognition),
                                        selected = false, // Set to true if you want to highlight it when active
                                        enabled = true,
                                        onClick = {
                                            onAutoSelected()
                                            expanded = false
                                            searchText = ""
                                        }
                                    )
                                    HorizontalDivider()
                                }
                                if (showNoneOption) {
                                    LargeDropdownMenuItem(
                                        text = stringResource(R.string.text_select_no_language),
                                        selected = false, // Set to true if you want to highlight it when active
                                        enabled = true,
                                        onClick = {
                                            onNoneSelected()
                                            expanded = false
                                            searchText = ""
                                        }
                                    )
                                    HorizontalDivider()
                                }
                                if (favoriteLanguages.any {
                                        it.code != "none" && it.code != "auto"
                                    }) {
                                    DropdownHeader(text = stringResource(R.string.text_favorites))
                                    favoriteLanguages.filter {
                                        it.code != "none" && it.code != "auto"
                                    }.forEach { language -> SingleSelectItem(language) }
                                    HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
                                }
                                val recentHistoryFiltered = languageHistory.filter {
                                    it !in favoriteLanguages && it.code != "none" && it.code != "auto"
                                }.takeLast(5)
                                if (recentHistoryFiltered.isNotEmpty()) {
                                    DropdownHeader(text = stringResource(R.string.text_recent_history))
                                    recentHistoryFiltered.forEach { language -> SingleSelectItem(language) }
                                    HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
                                }
                                val remainingLanguages = languages.filter {
                                    it !in favoriteLanguages && it !in recentHistoryFiltered && it.code != "none" && it.code != "auto"
                                }.sortedBy { it.name }
                                if (remainingLanguages.isNotEmpty()) {
                                    DropdownHeader(text = stringResource(R.string.text_all_languages))
                                    remainingLanguages.forEach { language -> SingleSelectItem(language) }
                                }
                            }
                        }
                    }

                    if (enableMultipleSelection) {
                        HorizontalDivider()
                        AppButton(
                            onClick = {
                                onLanguagesSelected(tempSelection)
                                selectedLanguagesCount = tempSelection.size
                                expanded = false
                                searchText = ""
                            },
                            modifier = Modifier
                                .padding(8.dp)
                                .fillMaxWidth()
                        ) {
                            Text(stringResource(R.string.label_done))
                        }
                    }

                    // Provides breathing room for system gestures at bottom of sheet
                    Spacer(modifier = Modifier.navigationBarsPadding().height(16.dp))
                }
            }
        }
    }
}

@Composable
fun SourceLanguageDropdown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel,
    autoEnabled: Boolean = false,
    iconEnabled: Boolean = true,
    noBorder: Boolean = false,
) {
    val selectedLanguage by languageViewModel.selectedSourceLanguage.collectAsState()
    val languageHistory by languageViewModel.languageHistory.collectAsState()

    BaseLanguageDropDown(
        modifier = modifier,
        languageViewModel = languageViewModel,
        selectedLanguage = selectedLanguage,
        onLanguageSelected = { lang ->
            languageViewModel.setSelectedSourceLanguage(lang)
            val updatedHistory = (languageHistory + lang).distinct().takeLast(5)
            languageViewModel.updateLanguageHistory(updatedHistory)
        },
        showAutoOption = autoEnabled,
        onAutoSelected = { languageViewModel.setSelectedSourceLanguage(0) },
        showNoneOption = false,
        enableMultipleSelection = false,
        iconEnabled = iconEnabled,
        noBorder = noBorder,
    )
}


@Composable
fun TargetLanguageDropdown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel,
    iconEnabled: Boolean = true,
    noBorder: Boolean = false,
) {
    val selectedLanguage by languageViewModel.selectedTargetLanguage.collectAsState()
    val languageHistory by languageViewModel.languageHistory.collectAsState()

    BaseLanguageDropDown(
        modifier = modifier,
        languageViewModel = languageViewModel,
        selectedLanguage = selectedLanguage,
        onLanguageSelected = { lang ->
            languageViewModel.setSelectedTargetLanguage(lang)
            val updatedHistory = (languageHistory + lang).distinct().takeLast(5)
            languageViewModel.updateLanguageHistory(updatedHistory)
        },
        showAutoOption = false,
        showNoneOption = false,
        enableMultipleSelection = false,
        iconEnabled = iconEnabled,
        noBorder = noBorder,

        )
}

@Composable
fun DictionaryLanguageDropDown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel
) {
    val selectedLanguage by languageViewModel.selectedDictionaryLanguage.collectAsState()
    val languageHistory by languageViewModel.languageHistory.collectAsState()

    BaseLanguageDropDown(
        modifier = modifier,
        languageViewModel = languageViewModel,
        selectedLanguage = selectedLanguage,
        onLanguageSelected = { lang ->
            languageViewModel.setSelectedDictionaryLanguage(lang)
            val updatedHistory = (languageHistory + lang).distinct().takeLast(5)
            languageViewModel.updateLanguageHistory(updatedHistory)
        },
        showAutoOption = false,
        showNoneOption = false,
        enableMultipleSelection = false
    )
}


@Composable
fun MultipleLanguageDropdown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel,
    onLanguagesSelected: (List<Language>) -> Unit,
    alternateLanguages: List<Language> = emptyList()
) {
    BaseLanguageDropDown(
        modifier = modifier,
        languageViewModel = languageViewModel,
        selectedLanguage = null,
        onLanguageSelected = {},
        showAutoOption = false,
        showNoneOption = true,
        onNoneSelected = { onLanguagesSelected(emptyList()) },
        enableMultipleSelection = true,
        onLanguagesSelected = onLanguagesSelected,
        alternateLanguages = alternateLanguages
    )
}

@Composable
fun SingleLanguageDropDown(
    modifier: Modifier = Modifier,
    languageViewModel: LanguageViewModel,
    selectedLanguage: Language?,
    onLanguageSelected: (Language) -> Unit,
    showAutoOption: Boolean = false,
    onAutoSelected: () -> Unit = {},
    showNoneOption: Boolean = false,
    onNoneSelected: () -> Unit = {},
    alternateLanguages: List<Language> = emptyList(),
    restrictToAlternateLanguages: Boolean = false,
    enabled: Boolean = true
) {
    val languageHistory by languageViewModel.languageHistory.collectAsState()

    BaseLanguageDropDown(
        modifier = modifier,
        languageViewModel = languageViewModel,
        selectedLanguage = selectedLanguage,
        onLanguageSelected = { lang ->
            onLanguageSelected(lang)

            val updatedHistory = (languageHistory + lang).distinctBy { it.code }.takeLast(5)
            languageViewModel.updateLanguageHistory(updatedHistory)
        },
        showAutoOption = showAutoOption,
        onAutoSelected = onAutoSelected,
        showNoneOption = showNoneOption,
        onNoneSelected = onNoneSelected,
        enableMultipleSelection = false,
        alternateLanguages = alternateLanguages,
        restrictToAlternateLanguages = restrictToAlternateLanguages,
        enabled = enabled,
        iconEnabled = enabled,
        noBorder = !enabled
    )
}