package eu.gaudian.translator.view.composable

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.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import eu.gaudian.translator.R
import eu.gaudian.translator.model.LanguageModel
import eu.gaudian.translator.model.communication.ApiProvider

@Composable
fun ApiModelDropDown(
    models: List<LanguageModel>,
    providers: List<ApiProvider>,
    selectedModel: LanguageModel?,
    onModelSelected: (LanguageModel?) -> Unit,
    enabled: Boolean = true
) {
    var expanded by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }

    val activeModels = models.filter { model -> providers.any { it.key == model.providerKey && (it.hasValidKey || it.isCustom) } }
    val groupedModels = activeModels.groupBy { it.providerKey }
    val providerNames = remember(providers) { providers.associate { it.key to it.displayName } }
    val providerStatuses = remember(providers) { providers.associate { it.key to (it.hasValidKey || it.isCustom) } }

    val filteredGroupedModels = remember(groupedModels, searchQuery) {
        if (searchQuery.isBlank()) {
            groupedModels
        } else {
            groupedModels.mapValues { (_, models) ->
                models.filter { model ->
                    model.displayName.contains(searchQuery, ignoreCase = true) ||
                            model.modelId.contains(searchQuery, ignoreCase = true) ||
                            model.description.contains(searchQuery, ignoreCase = true)
                }
            }.filterValues { it.isNotEmpty() }
        }
    }

    // Custom button content showing selected model and provider
    val buttonContent: @Composable () -> Unit = {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = selectedModel?.displayName ?: stringResource(R.string.text_select_model),
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                if (selectedModel != null) {
                    Text(
                        text = providerNames[selectedModel.providerKey] ?: selectedModel.providerKey,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
            Spacer(modifier = Modifier.width(8.dp))
            Icon(
                imageVector = if (expanded) AppIcons.ArrowDropUp else AppIcons.ArrowDropDown,
                contentDescription = if (expanded) stringResource(R.string.cd_collapse) else stringResource(R.string.cd_expand)
            )
        }
    }

    AppDropdownContainer(
        expanded = expanded,
        onDismissRequest = {
            expanded = false
            searchQuery = ""
        },
        onExpandRequest = { expanded = true },
        buttonText = "", // Not used with custom button content
        modifier = Modifier.fillMaxWidth(),
        enabled = enabled,
        showSearch = true,
        searchQuery = searchQuery,
        onSearchQueryChange = { searchQuery = it },
        searchPlaceholder = stringResource(R.string.label_search_models),
        buttonContent = buttonContent
    ) {
        Column(
            modifier = Modifier
                .heightIn(max = 400.dp)
                .verticalScroll(rememberScrollState())
        ) {
            if (filteredGroupedModels.isNotEmpty()) {
                filteredGroupedModels.entries.forEachIndexed { index, entry ->
                    val providerKey = entry.key
                    val providerModels = entry.value
                    val isActive = providerStatuses[providerKey] == true
                    val providerName = providerNames[providerKey] ?: providerKey

                    if (index > 0) HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))

                    // Provider header
                    AppDropdownMenuItem(
                        text = {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                modifier = Modifier.fillMaxWidth()
                            ) {
                                Icon(
                                    imageVector = if (isActive) AppIcons.CheckCircle else AppIcons.Warning,
                                    contentDescription = null,
                                    tint = if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.error,
                                    modifier = Modifier.size(16.dp)
                                )
                                Spacer(modifier = Modifier.width(8.dp))
                                Column(modifier = Modifier.weight(1f)) {
                                    Text(
                                        text = providerName,
                                        style = MaterialTheme.typography.labelMedium,
                                        fontWeight = FontWeight.Medium,
                                        color = if (isActive) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)
                                    )
                                    Text(
                                        text = stringResource(
                                            R.string.labels_1d_models,
                                            providerModels.size
                                        ),
                                        style = MaterialTheme.typography.labelSmall,
                                        color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                                    )
                                }
                            }
                        },
                        onClick = {},
                        enabled = false,
                        selected = false
                    )

                    // Models for this provider
                    providerModels.forEach { model ->
                        AppDropdownMenuItem(
                            text = {
                                Column(modifier = Modifier.fillMaxWidth()) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        modifier = Modifier.fillMaxWidth()
                                    ) {
                                        Text(
                                            text = model.displayName,
                                            style = MaterialTheme.typography.bodyMedium,
                                            modifier = Modifier.weight(1f),
                                            fontWeight = if (model == selectedModel) FontWeight.Medium else FontWeight.Normal
                                        )
                                        Spacer(modifier = Modifier.width(8.dp))
                                        ModelBadges(
                                            modelDisplayOrId = model.displayName.ifBlank { model.modelId },
                                            providerKey = model.providerKey,
                                        )
                                    }
                                    if (model.description.isNotBlank()) {
                                        Text(
                                            text = model.description,
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f),
                                            maxLines = 2,
                                            overflow = TextOverflow.Ellipsis
                                        )
                                    }
                                }
                            },
                            onClick = {
                                onModelSelected(model)
                                expanded = false
                                searchQuery = ""
                            },
                            selected = model == selectedModel
                        )
                    }
                }
            } else if (searchQuery.isNotBlank()) {
                AppDropdownMenuItem(
                    text = {
                        Text(
                            stringResource(R.string.text_no_models_found),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f),
                            modifier = Modifier.fillMaxWidth()
                        )
                    },
                    onClick = {},
                    enabled = false,
                    selected = false
                )
            }
        }
    }
}
