package app.dudu.app

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
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.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import app.dudu.design.DText
import app.dudu.design.IconCheck
import app.dudu.design.IconChevronLeft
import app.dudu.design.IconChevronRight
import app.dudu.design.LocalDuduPalette

/** 主 App 共用组件：按钮 / 卡片 / 列表行 / 顶栏 / 进度条 / 开关，颜色只取 DuduPalette。 */

/** 每屏唯一蓝色主按钮（44dp，圆角 6）。 */
@Composable
fun PrimaryButton(
    text: String,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    loading: Boolean = false,
    onClick: () -> Unit,
) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    val pressed by src.collectIsPressedAsState()
    val clickable = enabled && !loading
    Box(
        modifier
            .fillMaxWidth()
            .height(44.dp)
            .alpha(if (clickable) 1f else 0.55f)
            .clip(RoundedCornerShape(6.dp))
            .background(if (pressed && clickable) p.accentPress else p.accent)
            .clickable(interactionSource = src, indication = null, enabled = clickable, onClick = onClick),
        contentAlignment = Alignment.Center,
    ) {
        DText(if (loading) "请稍候" else text, 15.sp, p.textOnAccent, weight = FontWeight.Medium)
    }
}

/** ghost 次按钮：边框 + 文字色。 */
@Composable
fun GhostButton(text: String, modifier: Modifier = Modifier, onClick: () -> Unit) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    val pressed by src.collectIsPressedAsState()
    Box(
        modifier
            .fillMaxWidth()
            .height(44.dp)
            .clip(RoundedCornerShape(6.dp))
            .background(if (pressed) p.surface2 else Color.Transparent)
            .border(1.dp, p.border2, RoundedCornerShape(6.dp))
            .clickable(interactionSource = src, indication = null, onClick = onClick),
        contentAlignment = Alignment.Center,
    ) {
        DText(text, 15.sp, p.text1, weight = FontWeight.Medium)
    }
}

/** 卡片：surface-card 底 + border-1 + 圆角 14 + 内边距 16。 */
@Composable
fun DCard(modifier: Modifier = Modifier, content: @Composable ColumnScope.() -> Unit) {
    val p = LocalDuduPalette.current
    Column(
        modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(14.dp))
            .background(p.surfaceCard)
            .border(1.dp, p.border1, RoundedCornerShape(14.dp))
            .padding(16.dp),
        content = content,
    )
}

/** 列表行入口（标题 + 右箭头），danger 行用于退出登录。 */
@Composable
fun ListRow(title: String, danger: Boolean = false, onClick: () -> Unit) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    Row(
        Modifier
            .fillMaxWidth()
            .clickable(interactionSource = src, indication = null, onClick = onClick)
            .padding(vertical = 14.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        DText(title, 15.sp, if (danger) p.danger else p.text1)
        Spacer(Modifier.weight(1f))
        if (!danger) IconChevronRight(16.dp, p.text3)
    }
}

/** 顶栏：返回 + 标题（页面无二级导航时 onBack 为 null）。 */
@Composable
fun TopBar(title: String, onBack: (() -> Unit)?) {
    val p = LocalDuduPalette.current
    Row(
        Modifier
            .fillMaxWidth()
            .height(52.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        if (onBack != null) {
            val src = remember { MutableInteractionSource() }
            Box(
                Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .clickable(interactionSource = src, indication = null, onClick = onBack),
                contentAlignment = Alignment.Center,
            ) {
                IconChevronLeft(20.dp, p.text1)
            }
            Spacer(Modifier.width(4.dp))
        }
        DText(title, 17.sp, p.text1, weight = FontWeight.SemiBold)
    }
}

/** 浅蓝提示条（场景上下文）。 */
@Composable
fun ContextBanner(text: String) {
    val p = LocalDuduPalette.current
    Box(
        Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(10.dp))
            .background(p.accentSoft)
            .padding(horizontal = 14.dp, vertical = 10.dp),
    ) {
        DText(text, 13.sp, p.accentText)
    }
}

/** 进度条（试用用量等）。 */
@Composable
fun DProgressBar(fraction: Float, modifier: Modifier = Modifier) {
    val p = LocalDuduPalette.current
    Box(
        modifier
            .fillMaxWidth()
            .height(6.dp)
            .clip(RoundedCornerShape(999.dp))
            .background(p.surface2),
    ) {
        Box(
            Modifier
                .fillMaxWidth(fraction.coerceIn(0f, 1f))
                .fillMaxHeight()
                .clip(RoundedCornerShape(999.dp))
                .background(p.accent),
        )
    }
}

/** 状态徽标：positive（余额充足）/ warning（余额不足）/ neutral。 */
enum class BadgeKind { POSITIVE, WARNING, NEUTRAL }

@Composable
fun Badge(text: String, kind: BadgeKind) {
    val p = LocalDuduPalette.current
    val (bg, fg) = when (kind) {
        BadgeKind.POSITIVE -> p.positiveSoft to p.positive
        BadgeKind.WARNING -> p.warningSoft to p.warning
        BadgeKind.NEUTRAL -> p.surface2 to p.text2
    }
    Box(
        Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(bg)
            .padding(horizontal = 10.dp, vertical = 3.dp),
    ) {
        DText(text, 12.sp, fg, weight = FontWeight.Medium)
    }
}

/** 开关（SettingRow 用，36x22 胶囊 + 圆点）。 */
@Composable
fun DSwitch(checked: Boolean, onToggle: () -> Unit) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    Box(
        Modifier
            .width(40.dp)
            .height(24.dp)
            .clip(RoundedCornerShape(999.dp))
            .background(if (checked) p.accent else p.border2)
            .clickable(interactionSource = src, indication = null, onClick = onToggle)
            .padding(3.dp),
        contentAlignment = if (checked) Alignment.CenterEnd else Alignment.CenterStart,
    ) {
        Box(
            Modifier
                .size(18.dp)
                .clip(CircleShape)
                .background(p.textOnAccent),
        )
    }
}

/** 成功态绿对勾圆（56dp，购买完成 / 反馈成功共用）。 */
@Composable
fun SuccessCheckCircle() {
    val p = LocalDuduPalette.current
    Box(
        Modifier
            .size(56.dp)
            .clip(CircleShape)
            .background(p.positiveSoft),
        contentAlignment = Alignment.Center,
    ) {
        IconCheck(26.dp, p.positive)
    }
}

/** mock 四态切换 chip（离线联调，仅 debug 区显示）。 */
@Composable
fun StateChip(label: String, selected: Boolean, onClick: () -> Unit) {
    val p = LocalDuduPalette.current
    val src = remember { MutableInteractionSource() }
    Box(
        Modifier
            .clip(RoundedCornerShape(999.dp))
            .background(if (selected) p.accentSoft else p.surface2)
            .border(1.dp, if (selected) p.accent else p.border1, RoundedCornerShape(999.dp))
            .clickable(interactionSource = src, indication = null, onClick = onClick)
            .padding(horizontal = 14.dp, vertical = 7.dp),
    ) {
        DText(label, 13.sp, if (selected) p.accentText else p.text2)
    }
}

/** 错误/提示文案行（danger 色，表单下方）。 */
@Composable
fun NoticeText(text: String?, danger: Boolean = true) {
    val p = LocalDuduPalette.current
    if (text != null) {
        Spacer(Modifier.height(10.dp))
        DText(text, 13.sp, if (danger) p.danger else p.text2)
    }
}

/** 行间距快捷。 */
@Composable
fun VSpace(dp: Int) = Spacer(Modifier.height(dp.dp))

/** 横向间距快捷。 */
@Composable
fun HSpace(dp: Int) = Spacer(Modifier.width(dp.dp))

/** 分隔线。 */
@Composable
fun Divider1() {
    val p = LocalDuduPalette.current
    Box(
        Modifier
            .fillMaxWidth()
            .height(1.dp)
            .background(p.border1),
    )
}

/** 行排列快捷（垂直居中 + 8dp 间距）。 */
@Composable
fun CenterRow(modifier: Modifier = Modifier, content: @Composable () -> Unit) {
    Row(
        modifier,
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp),
    ) { content() }
}
