package wang.yaojia.webterm.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import wang.yaojia.webterm.designsystem.Spacing
import wang.yaojia.webterm.designsystem.WebTermCard
import wang.yaojia.webterm.designsystem.WebTermTheme
import wang.yaojia.webterm.session.AwayDigest
import wang.yaojia.webterm.wire.TimelineEvent

/**
 * # AwayDigestView (A22) — the "what happened while I was away" reattach summary.
 *
 * The Android analogue of the iOS away-digest banner (plan §1): shown ABOVE the terminal on the
 * first reconnect after a gap, summarising the [AwayDigest] reduced over the events since the user
 * left — tool-run and waiting counts plus done/stuck flags. Its **展开** ("expand") affordance opens
 * the A28 activity-timeline sheet via [onExpand] (this component only exposes the seam; A28 wires it).
 *
 * An [empty][AwayDigest.isEmpty] digest renders **nothing** (all-zero suppressed) — the caller
 * ([GateViewModel] holds `null` for an empty digest) normally never passes one, but the guard makes
 * the component safe in isolation. Recent-event labels are server-derived text rendered as **inert
 * [Text]** (no linkify/markdown, §8).
 */
@Composable
public fun AwayDigestView(
    digest: AwayDigest,
    onExpand: () -> Unit,
    modifier: Modifier = Modifier,
) {
    if (digest.isEmpty) return // all-zero suppressed; render nothing.
    WebTermCard(modifier = modifier.fillMaxWidth()) {
        Column(verticalArrangement = Arrangement.spacedBy(Spacing.xs4)) {
            Text(
                text = summaryLine(digest),
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurface,
            )
            digest.recent.lastOrNull()?.let { latest ->
                // INERT: server-derived phrase rendered verbatim, single line (§8).
                Text(
                    text = latest.label,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
            }
            Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                TextButton(onClick = onExpand) { Text(text = "展开") }
            }
        }
    }
}

/** The one-line count summary, e.g. "离开期间：3 次工具调用 · 1 次等待 · 已完成". Pure presentation. */
internal fun summaryLine(digest: AwayDigest): String {
    val parts = mutableListOf<String>()
    if (digest.toolRuns > 0) parts += "${digest.toolRuns} 次工具调用"
    if (digest.waitingCount > 0) parts += "${digest.waitingCount} 次等待"
    if (digest.sawDone) parts += "已完成"
    if (digest.sawStuck) parts += "疑似卡住"
    val body = if (parts.isEmpty()) "有活动" else parts.joinToString(" · ")
    return "离开期间：$body"
}

// ── Preview ─────────────────────────────────────────────────────────────────────

@Preview(name = "AwayDigestView")
@Composable
private fun AwayDigestViewPreview() {
    WebTermTheme {
        AwayDigestView(
            digest = AwayDigest(
                toolRuns = 3,
                waitingCount = 1,
                sawDone = true,
                sawStuck = false,
                recent = listOf(TimelineEvent(at = 0L, eventClass = "tool", toolName = "Bash", label = "ran Bash")),
            ),
            onExpand = {},
        )
    }
}
