package dev.kaizen.app.chat

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.expandVertically
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
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.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
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.draw.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import dev.kaizen.app.net.SearchSource
import dev.kaizen.app.net.ToolEvent
import dev.kaizen.app.R
import dev.kaizen.app.ui.shape.KaizenShapes
import dev.kaizen.app.ui.theme.KaizenSemanticColors
import dev.kaizen.app.ui.theme.LocalKaizenAccent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import dev.kaizen.app.ui.icon.KaizenIcons

@Composable
fun ReasoningBlock(reasoning: String, streaming: Boolean = false) {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current
    var expanded by remember { mutableStateOf(streaming) }

    val bg = accent.primary.copy(alpha = if (isDark) 0.06f else 0.04f)
    val borderBrush = remember(isDark, accent) {
        Brush.verticalGradient(
            listOf(
                accent.primary.copy(alpha = if (isDark) 0.20f else 0.15f),
                accent.primary.copy(alpha = if (isDark) 0.05f else 0.03f),
            )
        )
    }

    Column(
        Modifier
            .fillMaxWidth()
            .clip(KaizenShapes.md)
            .background(bg)
            .border(0.8.dp, borderBrush, KaizenShapes.md)
    ) {
        Row(
            Modifier
                .fillMaxWidth()
                .clickable { expanded = !expanded }
                .padding(horizontal = 14.dp, vertical = 10.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(KaizenIcons.Brain, null, tint = accent.primary.copy(alpha = 0.75f), modifier = Modifier.size(17.dp))
            Spacer(Modifier.width(9.dp))
            Text(
                stringResource(R.string.stream_reasoning),
                color = cs.onSurfaceVariant.copy(alpha = 0.75f),
                fontSize = 13.sp,
                fontWeight = FontWeight.Medium,
                modifier = Modifier.weight(1f),
            )
            Icon(
                if (expanded) KaizenIcons.ChevronUp else KaizenIcons.ChevronDown,
                null, tint = cs.onSurfaceVariant.copy(alpha = 0.40f), modifier = Modifier.size(15.dp),
            )
        }
        AnimatedVisibility(expanded, enter = expandVertically(), exit = shrinkVertically()) {
            Text(
                reasoning,
                color = cs.onSurfaceVariant.copy(alpha = 0.70f),
                fontSize = 13.sp,
                lineHeight = 20.sp,
                modifier = Modifier.padding(start = 14.dp, end = 14.dp, bottom = 12.dp),
            )
        }
    }
}

@Composable
fun ToolEventsBlock(tools: List<ToolEvent>, streaming: Boolean = false) {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current

    val completed = mutableListOf<ToolEvent>()
    val inProgress = mutableListOf<String>()
    val seen = mutableSetOf<String>()
    var thinking = false
    var analyzing: String? = null

    for (ev in tools) {
        when (ev.type) {
            "thinking" -> { thinking = true; analyzing = null }
            "analyzing" -> { analyzing = ev.name; thinking = false }
            "start" -> {
                analyzing = null; thinking = false
                if (ev.name !in seen) { seen.add(ev.name); inProgress.add(ev.name) }
            }
            "end", "error" -> {
                inProgress.remove(ev.name)
                completed.add(ev)
            }
        }
    }

    val hasContent = analyzing != null || thinking || completed.isNotEmpty() || inProgress.isNotEmpty()
    if (!hasContent) return

    Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
        if (analyzing != null) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(KaizenIcons.FileText, null, tint = accent.primary.copy(alpha = 0.6f), modifier = Modifier.size(14.dp))
                Spacer(Modifier.width(6.dp))
                Text(stringResource(R.string.stream_tool_analyzing, analyzing!!), color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp)
            }
        }
        if (thinking && analyzing == null && completed.isEmpty() && inProgress.isEmpty()) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(KaizenIcons.Sparkles, null, tint = accent.primary.copy(alpha = 0.6f), modifier = Modifier.size(14.dp))
                Spacer(Modifier.width(6.dp))
                Text(stringResource(R.string.stream_tool_thinking), color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp)
            }
        }
        completed.forEach { tool ->
            Row(verticalAlignment = Alignment.CenterVertically) {
                val icon = if (tool.type == "error") KaizenIcons.AlertCircle else KaizenIcons.Check
                val tint = if (tool.type == "error") KaizenSemanticColors.error else KaizenSemanticColors.success
                Icon(icon, null, tint = tint, modifier = Modifier.size(14.dp))
                Spacer(Modifier.width(6.dp))
                Text(tool.name, color = cs.onSurfaceVariant.copy(alpha = 0.6f), fontSize = 12.sp)
                if (tool.elapsed != null) {
                    Spacer(Modifier.width(4.dp))
                    Text("${tool.elapsed}ms", color = cs.onSurfaceVariant.copy(alpha = 0.35f), fontSize = 11.sp)
                }
            }
        }
        inProgress.forEach { name ->
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(KaizenIcons.Wrench, null, tint = accent.primary.copy(alpha = 0.6f), modifier = Modifier.size(14.dp))
                Spacer(Modifier.width(6.dp))
                Text(name, color = cs.onSurfaceVariant.copy(alpha = 0.7f), fontSize = 12.sp, fontWeight = FontWeight.Medium)
            }
        }
    }
}

@Composable
fun SourcesBlock(sources: List<SearchSource>, query: String = "") {
    val cs = MaterialTheme.colorScheme
    val isDark = isSystemInDarkTheme()
    val accent = LocalKaizenAccent.current
    var expanded by remember { mutableStateOf(false) }
    val context = LocalContext.current

    Column {
        Row(
            Modifier
                .clickable { expanded = !expanded }
                .padding(vertical = 4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Icon(KaizenIcons.Globe, null, tint = cs.onSurfaceVariant.copy(alpha = 0.55f), modifier = Modifier.size(14.dp))
            Spacer(Modifier.width(6.dp))
            Text(
                stringResource(R.string.stream_sources) + " (${sources.size})",
                color = cs.onSurfaceVariant.copy(alpha = 0.55f),
                fontSize = 12.sp,
                fontWeight = FontWeight.Medium,
            )
            Spacer(Modifier.width(4.dp))
            Icon(
                if (expanded) KaizenIcons.ChevronUp else KaizenIcons.ChevronDown,
                null, tint = cs.onSurfaceVariant.copy(alpha = 0.35f), modifier = Modifier.size(13.dp),
            )
        }
        AnimatedVisibility(expanded, enter = expandVertically(), exit = shrinkVertically()) {
            Column(verticalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.padding(top = 4.dp)) {
                sources.forEach { source ->
                    SourceCard(source, isDark, accent) {
                        try {
                            val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(source.url))
                            context.startActivity(intent)
                        } catch (_: Exception) { }
                    }
                }
            }
        }
    }
}

@Composable
private fun SourceCard(source: SearchSource, isDark: Boolean, accent: dev.kaizen.app.ui.theme.themes.KaizenAccentScheme, onClick: () -> Unit) {
    val cs = MaterialTheme.colorScheme
    val bg = if (isDark) Color.White.copy(alpha = 0.05f) else Color.Black.copy(alpha = 0.03f)
    val borderBrush = remember(isDark) {
        Brush.verticalGradient(
            listOf(
                if (isDark) Color.White.copy(alpha = 0.10f) else Color.Black.copy(alpha = 0.06f),
                if (isDark) Color.White.copy(alpha = 0.03f) else Color.Black.copy(alpha = 0.02f),
            )
        )
    }

    val domain = remember(source.url) {
        try {
            java.net.URI(source.url).host?.removePrefix("www.") ?: source.url
        } catch (_: Exception) { source.url }
    }

    Column(
        Modifier
            .fillMaxWidth()
            .clip(KaizenShapes.md)
            .background(bg)
            .border(0.8.dp, borderBrush, KaizenShapes.md)
            .clickable(onClick = onClick)
            .padding(horizontal = 14.dp, vertical = 10.dp),
    ) {
        Text(
            source.title.ifEmpty { domain },
            color = cs.onBackground,
            fontSize = 13.sp,
            fontWeight = FontWeight.Medium,
            maxLines = 2,
            overflow = TextOverflow.Ellipsis,
        )
        Spacer(Modifier.height(2.dp))
        Text(
            domain,
            color = accent.primary.copy(alpha = 0.65f),
            fontSize = 11.sp,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        if (source.snippet.isNotBlank()) {
            Spacer(Modifier.height(3.dp))
            Text(
                source.snippet,
                color = cs.onSurfaceVariant.copy(alpha = 0.50f),
                fontSize = 11.sp,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis,
            )
        }
    }
}
