package com.jishisongfu.duobibi.ui.tools

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
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.saveable.rememberSaveable
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.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.jishisongfu.duobibi.ui.DbbProgressBar
import com.jishisongfu.duobibi.ui.TagChip
import com.jishisongfu.duobibi.ui.fmtYuan
import com.jishisongfu.duobibi.ui.theme.DbbColors

private data class Tier(val threshold: Double, val reduction: Double)

private val TIERS = listOf(
    Tier(300.0, 50.0), Tier(600.0, 100.0), Tier(1000.0, 200.0), Tier(1500.0, 300.0),
)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BundleCalculatorScreen(onBack: () -> Unit) {
    var cartText by rememberSaveable { mutableStateOf("") }

    Scaffold(
        containerColor = DbbColors.Bg,
        topBar = { CalcBar("凑单计算器", onBack) },
    ) { padding ->
        Column(
            Modifier
                .padding(padding)
                .fillMaxSize()
                .background(DbbColors.Bg)
                .verticalScroll(rememberScrollState())
                .padding(14.dp),
        ) {
            // 顶部说明(teal 浅底,去 sky)
            Box(
                Modifier
                    .fillMaxWidth()
                    .clip(RoundedCornerShape(12.dp))
                    .background(DbbColors.TealBg)
                    .padding(horizontal = 14.dp, vertical = 12.dp),
            ) {
                Text(
                    "阶梯满减:满 300−50 / 满 600−100 / 满 1000−200 / 满 1500−300。看看再凑一点是不是反而更省。",
                    color = DbbColors.TealDark, fontSize = 12.sp,
                )
            }
            Spacer(Modifier.height(12.dp))

            // 输入框
            OutlinedTextField(
                value = cartText,
                onValueChange = { cartText = it.numeric() },
                label = { Text("当前购物车金额(元)") },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                singleLine = true,
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(14.dp),
            )
            Spacer(Modifier.height(12.dp))

            val cart = cartText.toDoubleOrNull()
            if (cart != null && cart > 0) {
                val hit = TIERS.filter { cart >= it.threshold }.maxByOrNull { it.threshold }
                val next = TIERS.firstOrNull { it.threshold > cart }
                val currentFinal = if (hit != null) cart - hit.reduction else cart

                // 当前实付卡(绿色)
                CurrentPayCard(currentFinal, hit)
                Spacer(Modifier.height(12.dp))

                // 进度 + 阶梯
                Card(
                    Modifier.fillMaxWidth(),
                    colors = CardDefaults.cardColors(containerColor = DbbColors.Card),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                    shape = RoundedCornerShape(16.dp),
                ) {
                    Column(Modifier.padding(14.dp)) {
                        if (next != null) {
                            ProgressBlock(cart, next)
                            Spacer(Modifier.height(13.dp))
                            Box(Modifier.fillMaxWidth().height(1.dp).background(DbbColors.Border))
                            Spacer(Modifier.height(13.dp))
                        }
                        Text("满减阶梯", fontWeight = FontWeight.Bold, color = DbbColors.Ink, fontSize = 13.sp)
                        Spacer(Modifier.height(8.dp))
                        TIERS.forEach { t ->
                            TierRow(
                                t = t,
                                cart = cart,
                                isCurrent = hit?.threshold == t.threshold,
                                isNext = next?.threshold == t.threshold,
                            )
                            Spacer(Modifier.height(2.dp))
                        }
                    }
                }
                Spacer(Modifier.height(12.dp))

                // 凑单建议(teal 浅底带深 teal 边,去 gold)
                if (next != null) {
                    val gap = next.threshold - cart
                    val nextFinal = (cart + gap) - next.reduction
                    val diff = currentFinal - nextFinal
                    val msg = if (diff > 0)
                        "💡 再凑 ¥${fmtYuan(gap)} 到「满 ${fmtYuan(next.threshold)} 减 ${fmtYuan(next.reduction)}」,实付反而少花 ¥${fmtYuan(diff)}!"
                    else
                        "再凑 ¥${fmtYuan(gap)} 到下一档,实付会多花 ¥${fmtYuan(-diff)},不划算。"
                    Box(
                        Modifier
                            .fillMaxWidth()
                            .clip(RoundedCornerShape(14.dp))
                            .background(if (diff > 0) DbbColors.TealBg else DbbColors.Fill)
                            .border(
                                width = if (diff > 0) 1.dp else 0.dp,
                                color = if (diff > 0) DbbColors.Teal else Color.Transparent,
                                shape = RoundedCornerShape(14.dp),
                            )
                            .padding(14.dp),
                    ) {
                        Text(
                            msg,
                            color = if (diff > 0) DbbColors.TealDark else DbbColors.InkSec,
                            fontWeight = FontWeight.SemiBold,
                            fontSize = 14.sp,
                        )
                    }
                }
                Spacer(Modifier.height(20.dp))
            }
        }
    }
}

@Composable
private fun CurrentPayCard(currentFinal: Double, hit: Tier?) {
    Box(
        Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(14.dp))
            .background(DbbColors.SaveBg)
            .padding(14.dp),
    ) {
        Row(verticalAlignment = Alignment.Top) {
            Column(Modifier.weight(1f)) {
                Text("当前实付", color = DbbColors.InkSec, fontSize = 12.sp)
                Spacer(Modifier.height(2.dp))
                Text(
                    "¥${fmtYuan(currentFinal)}",
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 24.sp,
                    color = DbbColors.Save,
                )
            }
            Column(horizontalAlignment = Alignment.End) {
                Text("满减优惠", color = DbbColors.InkTer, fontSize = 11.sp)
                Spacer(Modifier.height(2.dp))
                val text = if (hit != null)
                    "已减 ¥${fmtYuan(hit.reduction)}"
                else
                    "未达门槛"
                val color = if (hit != null) DbbColors.Save else DbbColors.InkSec
                Text(text, color = color, fontWeight = FontWeight.Bold, fontSize = 15.sp)
            }
        }
    }
}

@Composable
private fun ProgressBlock(cart: Double, next: Tier) {
    val gap = next.threshold - cart
    val frac = (cart / next.threshold).toFloat().coerceIn(0f, 1f)
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text(
            "距「满 ${fmtYuan(next.threshold)} 减 ${fmtYuan(next.reduction)}」",
            color = DbbColors.Ink, fontWeight = FontWeight.Bold, fontSize = 13.sp,
            modifier = Modifier.weight(1f),
        )
        Text(
            "还差 ¥${fmtYuan(gap)}",
            color = DbbColors.Up, fontWeight = FontWeight.SemiBold, fontSize = 13.sp,
        )
    }
    Spacer(Modifier.height(8.dp))
    DbbProgressBar(fraction = frac, color = DbbColors.Teal)
    Spacer(Modifier.height(5.dp))
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text("¥0", color = DbbColors.InkTer, fontSize = 11.sp)
        Spacer(Modifier.weight(1f))
        Text(
            "¥${fmtYuan(cart)} / ¥${fmtYuan(next.threshold)}",
            color = DbbColors.Teal, fontWeight = FontWeight.SemiBold, fontSize = 11.sp,
        )
        Spacer(Modifier.weight(1f))
        Text("¥${fmtYuan(next.threshold)}", color = DbbColors.InkTer, fontSize = 11.sp)
    }
}

@Composable
private fun TierRow(t: Tier, cart: Double, isCurrent: Boolean, isNext: Boolean) {
    // 本档实付:若 cart 已 ≥ 门槛,实付=cart-reduction;否则按刚好凑齐计算
    val realPay = if (cart >= t.threshold) cart - t.reduction else t.threshold - t.reduction
    val bg = if (isCurrent) DbbColors.TealBg else Color.Transparent
    Box(
        Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(10.dp))
            .background(bg)
            .padding(horizontal = 10.dp, vertical = 7.dp),
    ) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            Text(
                "满 ${fmtYuan(t.threshold)} 减 ${fmtYuan(t.reduction)}",
                color = if (isCurrent) DbbColors.TealDark else DbbColors.InkSec,
                fontWeight = if (isCurrent) FontWeight.Bold else FontWeight.Normal,
                fontSize = 13.sp,
                modifier = Modifier.weight(1f),
            )
            Text(
                "实付 ¥${fmtYuan(realPay)}",
                color = if (isCurrent) DbbColors.TealDark else DbbColors.InkTer,
                fontSize = 12.sp,
            )
            if (isCurrent) {
                Spacer(Modifier.width(8.dp))
                TagChip("当前档", bg = DbbColors.Teal, fg = Color.White)
            } else if (isNext) {
                Spacer(Modifier.width(8.dp))
                TagChip("下一档", bg = DbbColors.Teal, fg = Color.White)
            }
        }
    }
}
