package app.dudu.ime.ui

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
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.draw.scale
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.gestures.awaitEachGesture
import androidx.compose.foundation.gestures.awaitFirstDown
import app.dudu.design.DText
import app.dudu.design.IconMic
import app.dudu.design.LocalDuduPalette

/** MicBar 四态（设计规范 3.3，文案内置逐字对照 MicBar.jsx）。 */
enum class MicBarState { Idle, Recording, Disabled, Quota }

/**
 * 大麦克风条：高 56 / 全宽 / 胶囊 999 / 15sp 600。
 * 手势：按下开始 → 上滑超过 48dp 进入"将取消"（视觉转 danger + 文案"松开取消"）→
 * 松开按是否越阈值分流 onRelease / onCancel。
 */
@Composable
fun MicBar(
    state: MicBarState,
    willCancel: Boolean,
    onPressDown: () -> Unit,
    onDrag: (beyondCancelThreshold: Boolean) -> Unit,
    onRelease: () -> Unit,
    onCancel: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val p = LocalDuduPalette.current
    var pressed by remember { mutableStateOf(false) }

    val bg by animateColorAsState(
        targetValue = when {
            state == MicBarState.Disabled -> p.surface3
            state == MicBarState.Quota -> p.warning
            state == MicBarState.Recording && willCancel -> p.danger
            state == MicBarState.Recording -> p.positive
            pressed -> p.accentPress
            else -> p.accent
        },
        animationSpec = tween(120),
        label = "micbar-bg",
    )
    // 移动端按压缩 0.97（设计规范）
    val scale by animateFloatAsState(
        targetValue = if (pressed && state == MicBarState.Idle) 0.97f else 1f,
        animationSpec = tween(120),
        label = "micbar-scale",
    )

    Row(
        modifier = modifier
            .fillMaxWidth()
            .height(56.dp)
            .scale(scale)
            .clip(RoundedCornerShape(999.dp))
            .background(bg)
            .pointerInput(state) {
                // 等价 touch-action:none——独占整条手势，竖向位移用于取消判定而非滚动
                awaitEachGesture {
                    val down = awaitFirstDown()
                    down.consume()
                    pressed = true
                    onPressDown()
                    val cancelPx = 48.dp.toPx()
                    var beyond = false
                    while (true) {
                        val event = awaitPointerEvent()
                        val change = event.changes.firstOrNull { it.id == down.id } ?: break
                        if (!change.pressed) break
                        beyond = (change.position.y - down.position.y) < -cancelPx
                        onDrag(beyond)
                        change.consume()
                    }
                    pressed = false
                    if (beyond) onCancel() else onRelease()
                }
            },
        horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.CenterHorizontally),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        when (state) {
            MicBarState.Idle -> {
                IconMic(20.dp, p.textOnAccent)
                DText("按住说话", 15.sp, p.textOnAccent, weight = FontWeight.SemiBold)
            }
            MicBarState.Recording -> {
                Waveform(bars = 9, height = 18.dp, color = p.textOnAccent.copy(alpha = 0.95f))
                DText(
                    if (willCancel) "松开取消" else "松开完成 · 上滑取消",
                    15.sp, p.textOnAccent, weight = FontWeight.SemiBold,
                )
            }
            MicBarState.Disabled -> {
                DText("打开 dudu App 登录", 15.sp, p.text3, weight = FontWeight.SemiBold)
            }
            MicBarState.Quota -> {
                DText("今日试用已用完，去购买时长", 15.sp, p.textOnAccent, weight = FontWeight.SemiBold)
            }
        }
    }
}
