package dev.kaizen.app.chat

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import dev.kaizen.app.ui.shape.KaizenShapes
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.kaizen.app.net.KaizenModel
import dev.kaizen.app.R
import androidx.compose.ui.res.stringResource
import dev.kaizen.app.ui.theme.KaizenSemanticColors
import dev.kaizen.app.ui.theme.LocalKaizenAccent
import dev.kaizen.app.haptics.rememberHaptics
import dev.kaizen.app.ui.icon.KaizenIcons

/** Human label + composite-id resolver for the top pill — falls back to a de-prefixed id. */
fun modelDisplayName(modelId: String, models: List<KaizenModel>): String =
    models.firstOrNull { it.id == modelId }?.name ?: modelId.substringAfter(":")

/** The glass top pill showing the active model — tap opens [ModelSheet]. */
@Composable
fun ModelPill(label: String, onClick: () -> Unit, modifier: Modifier = Modifier) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    Row(
        modifier = modifier
            .clip(KaizenShapes.xl)
            .background(cs.surface.copy(alpha = 0.92f))
            .border(1.dp, cs.onSurface.copy(alpha = 0.08f), KaizenShapes.xl)
            .clickable { onClick() }
            .padding(start = 14.dp, end = 8.dp, top = 9.dp, bottom = 9.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        Text(
            label,
            color = cs.onBackground,
            fontSize = 14.sp,
            fontWeight = FontWeight.SemiBold,
            maxLines = 1,
        )
        Icon(
            KaizenIcons.ChevronDown,
            contentDescription = null,
            tint = cs.onSurfaceVariant,
            modifier = Modifier.size(18.dp),
        )
    }
}

/** A logical group of models in the picker (Favorites, then by publisher/provider). */
private data class ModelGroup(val label: String, val models: List<KaizenModel>)

private fun groupFor(m: KaizenModel): String = when {
    m.provider == "vertex" || m.id.startsWith("vertex:") -> "Vertex AI"
    else -> "OpenRouter"
}

private fun buildGroups(models: List<KaizenModel>, favorites: Set<String>, query: String, favoritesLabel: String = "★ Favorites"): List<ModelGroup> {
    val q = query.trim().lowercase()
    val filtered = if (q.isEmpty()) models
    else models.filter { it.name?.lowercase()?.contains(q) == true || it.id.lowercase().contains(q) }

    val groups = mutableListOf<ModelGroup>()
    val favs = filtered.filter { it.id in favorites }
    if (favs.isNotEmpty()) groups += ModelGroup(favoritesLabel, favs)

    // Group models, sorting group labels (Vertex first, then OpenRouter)
    filtered.groupBy { groupFor(it) }
        .toSortedMap(compareBy({ if (it == "Vertex AI") "" else it.lowercase() }))
        .forEach { (label, list) -> groups += ModelGroup(label, list.sortedBy { it.name }) }
    return groups
}

data class ProviderInfo(
    val name: String,
    val color: Color,
)

fun getProviderInfo(modelId: String, provider: String?): ProviderInfo {
    return when {
        provider == "vertex" || modelId.startsWith("vertex:") -> {
            ProviderInfo("Vertex AI", KaizenSemanticColors.indigo)
        }
        else -> {
            ProviderInfo("OpenRouter", KaizenSemanticColors.success)
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ModelSheet(
    models: List<KaizenModel>,
    selectedModelId: String,
    favorites: Set<String>,
    onSelectModel: (String) -> Unit,
    onToggleFavorite: (String) -> Unit,
    onDismiss: () -> Unit,
) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    var query by remember { mutableStateOf("") }
    val favLabel = stringResource(R.string.model_favorites_group)
    val groups = remember(models, favorites, query) { buildGroups(models, favorites, query, favLabel) }

    ModalBottomSheet(onDismissRequest = onDismiss, sheetState = sheetState) {
        Column(Modifier.fillMaxWidth().padding(horizontal = 20.dp)) {
            // --- Title ---
            Text(
                stringResource(R.string.model_sheet_title),
                color = cs.onBackground,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(bottom = 14.dp, start = 4.dp),
            )

            // --- Custom Premium Glassmorphic Search ---
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .clip(KaizenShapes.md)
                    .background(cs.surfaceVariant.copy(alpha = 0.4f))
                    .border(1.dp, cs.onSurface.copy(alpha = 0.06f), KaizenShapes.md)
                    .padding(horizontal = 14.dp, vertical = 11.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    KaizenIcons.Search,
                    contentDescription = null,
                    tint = cs.onSurfaceVariant.copy(alpha = 0.6f),
                    modifier = Modifier.size(18.dp)
                )
                Spacer(Modifier.width(8.dp))
                Box(Modifier.weight(1f)) {
                    if (query.isEmpty()) {
                        Text(
                            stringResource(R.string.model_search_placeholder),
                            color = cs.onSurfaceVariant.copy(alpha = 0.5f),
                            fontSize = 14.sp
                        )
                    }
                    BasicTextField(
                        value = query,
                        onValueChange = { query = it },
                        singleLine = true,
                        cursorBrush = SolidColor(accent.primary),
                        textStyle = androidx.compose.ui.text.TextStyle(
                            color = cs.onBackground,
                            fontSize = 14.sp
                        ),
                        modifier = Modifier.fillMaxWidth()
                    )
                }
                if (query.isNotEmpty()) {
                    Icon(
                        KaizenIcons.X,
                        contentDescription = stringResource(R.string.model_search_clear),
                        tint = cs.onSurfaceVariant.copy(alpha = 0.6f),
                        modifier = Modifier
                            .size(18.dp)
                            .clickable { query = "" }
                    )
                }
            }

            Spacer(Modifier.size(12.dp))

            LazyColumn(Modifier.fillMaxWidth().heightIn(max = 480.dp)) {
                if (groups.isEmpty()) {
                    item {
                        Text(
                            if (models.isEmpty()) stringResource(R.string.model_connecting) else stringResource(R.string.model_no_results),
                            color = cs.onSurfaceVariant,
                            fontSize = 14.sp,
                            modifier = Modifier.padding(vertical = 24.dp),
                        )
                    }
                }
                groups.forEach { group ->
                    item(key = "h_${group.label}") {
                        Text(
                            group.label.uppercase(),
                            color = cs.onSurfaceVariant.copy(alpha = 0.5f),
                            fontSize = 11.sp,
                            fontWeight = FontWeight.Bold,
                            letterSpacing = 0.8.sp,
                            modifier = Modifier.padding(top = 16.dp, bottom = 6.dp, start = 4.dp),
                        )
                    }
                    items(group.models, key = { "${group.label}_${it.id}" }) { model ->
                        ModelRow(
                            model = model,
                            selected = model.id == selectedModelId,
                            favorite = model.id in favorites,
                            onClick = { onSelectModel(model.id); onDismiss() },
                            onToggleFavorite = { onToggleFavorite(model.id) },
                        )
                    }
                }
                item { Spacer(Modifier.size(24.dp)) }
            }
        }
    }
}

@Composable
private fun ModelRow(
    model: KaizenModel,
    selected: Boolean,
    favorite: Boolean,
    onClick: () -> Unit,
    onToggleFavorite: () -> Unit,
) {
    val cs = MaterialTheme.colorScheme
    val accent = LocalKaizenAccent.current
    val haptics = rememberHaptics()
    val providerInfo = remember(model.id, model.provider) { getProviderInfo(model.id, model.provider) }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
            .clip(KaizenShapes.md)
            .background(
                if (selected) {
                    accent.primary.copy(alpha = 0.08f)
                } else {
                    cs.surfaceVariant.copy(alpha = 0.15f)
                }
            )
            .border(
                width = 1.dp,
                color = if (selected) accent.primary.copy(alpha = 0.25f) else Color.Transparent,
                shape = KaizenShapes.md
            )
            .clickable { haptics.tick(); onClick() }
            .padding(horizontal = 14.dp, vertical = 12.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        // Dynamic Colored Badge for Provider (Vertex AI or OpenRouter)
        Box(
            modifier = Modifier
                .clip(KaizenShapes.xs)
                .background(providerInfo.color.copy(alpha = 0.15f))
                .padding(horizontal = 8.dp, vertical = 4.dp)
        ) {
            Text(
                text = providerInfo.name,
                color = providerInfo.color,
                fontSize = 10.sp,
                fontWeight = FontWeight.Bold,
                letterSpacing = 0.5.sp
            )
        }

        Spacer(Modifier.size(12.dp))

        // Model Name & Clean Technical ID
        Column(modifier = Modifier.weight(1f)) {
            Text(
                model.name ?: model.id,
                color = cs.onBackground,
                fontSize = 15.sp,
                fontWeight = if (selected) FontWeight.SemiBold else FontWeight.Medium,
            )
            Text(
                text = model.id.substringAfter(":"),
                color = cs.onSurfaceVariant.copy(alpha = 0.4f),
                fontSize = 11.sp,
                maxLines = 1,
            )
        }

        // Sleek Star Toggle Button
        Box(
            Modifier
                .size(36.dp)
                .clip(KaizenShapes.circle)
                .clickable { haptics.tick(); onToggleFavorite() },
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                imageVector = if (favorite) KaizenIcons.Star else KaizenIcons.StarOff,
                contentDescription = stringResource(R.string.model_favorite),
                tint = if (favorite) accent.primary else cs.onSurfaceVariant.copy(alpha = 0.35f),
                modifier = Modifier.size(20.dp),
            )
        }

        if (selected) {
            Spacer(Modifier.size(4.dp))
            Icon(
                KaizenIcons.Check,
                contentDescription = stringResource(R.string.model_selected),
                tint = accent.primary,
                modifier = Modifier.size(20.dp)
            )
        }
    }
}
