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.horizontalScroll
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.FilterChip
import androidx.compose.material3.FilterChipDefaults
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.fmtYuan
import com.jishisongfu.duobibi.ui.theme.DbbColors
import kotlin.math.pow

private val TERMS = listOf(3, 6, 12, 18, 24)

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun InstallmentCalculatorScreen(onBack: () -> Unit) {
    var principalText by rememberSaveable { mutableStateOf("6000") }
    var term by rememberSaveable { mutableStateOf(12) }
    var rateText by rememberSaveable { mutableStateOf("0.66") }

    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(
                    "「免息分期」常带手续费。销售说的「年化」多按 月费率×12 算,远低于真实成本。本工具用 IRR 还原真实年化。",
                    color = DbbColors.TealDark, fontSize = 12.sp,
                )
            }
            Spacer(Modifier.height(12.dp))

            // 输入行:分期金额 + 手续费率(并排)
            Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                OutlinedTextField(
                    value = principalText,
                    onValueChange = { principalText = it.numeric() },
                    label = { Text("分期金额(元)", fontSize = 11.sp) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    singleLine = true,
                    modifier = Modifier.width(150.dp),
                    shape = RoundedCornerShape(14.dp),
                )
                OutlinedTextField(
                    value = rateText,
                    onValueChange = { rateText = it.numeric() },
                    label = { Text("每期手续费率(%)", fontSize = 11.sp) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    singleLine = true,
                    modifier = Modifier.weight(1f),
                    shape = RoundedCornerShape(14.dp),
                )
            }
            Spacer(Modifier.height(12.dp))

            Text("分期数", color = DbbColors.InkSec, fontSize = 12.sp)
            Spacer(Modifier.height(6.dp))
            Row(
                Modifier.fillMaxWidth().horizontalScroll(rememberScrollState()),
                horizontalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                TERMS.forEach { t ->
                    FilterChip(
                        selected = term == t,
                        onClick = { term = t },
                        label = { Text("${t}期", fontSize = 13.sp) },
                        colors = FilterChipDefaults.filterChipColors(
                            selectedContainerColor = DbbColors.Teal,
                            selectedLabelColor = Color.White,
                        ),
                    )
                }
            }
            Spacer(Modifier.height(14.dp))

            val principal = principalText.toDoubleOrNull()
            val monthlyRate = rateText.toDoubleOrNull()?.div(100.0)
            if (principal != null && principal > 0 && monthlyRate != null && monthlyRate > 0) {
                val perFee = principal * monthlyRate
                val installment = principal / term + perFee
                val total = installment * term
                val extra = total - principal
                val nominal = monthlyRate * 12
                val real = solveMonthlyIrr(principal, installment, term) * 12
                val ratio = if (nominal > 0) real / nominal else 0.0

                // 还款明细卡
                BreakdownCard(
                    installment = installment,
                    term = term,
                    principalPerTerm = principal / term,
                    feePerTerm = perFee,
                    total = total,
                    principal = principal,
                    extra = extra,
                )
                Spacer(Modifier.height(12.dp))

                // 名义 vs 真实 年化
                Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                    RateBox(
                        title = "名义年化",
                        value = "%.2f%%".format(nominal * 100),
                        sub = "月费率 ×12",
                        bg = DbbColors.Fill,
                        fg = DbbColors.InkSec,
                        modifier = Modifier.weight(1f),
                    )
                    RateBox(
                        title = "真实年化(IRR)",
                        value = "%.2f%%".format(real * 100),
                        sub = "≈ 名义的 ${"%.2f".format(ratio)} 倍",
                        bg = DbbColors.UpBg,
                        fg = DbbColors.Up,
                        modifier = Modifier.weight(1f),
                    )
                }
                Spacer(Modifier.height(10.dp))

                // 警示卡:语义上是"提醒真实成本",用 Up 红更准确(也回收 Gold 第四色)
                Box(
                    Modifier
                        .fillMaxWidth()
                        .clip(RoundedCornerShape(12.dp))
                        .background(Color.White)
                        .border(
                            width = 1.dp,
                            color = DbbColors.UpBg,
                            shape = RoundedCornerShape(12.dp),
                        )
                        .padding(horizontal = 14.dp, vertical = 12.dp),
                ) {
                    Text(
                        "⚠️ 本金逐月减少,手续费却按全额每期照收,真实资金成本接近一般信用贷。分期前请按真实年化评估是否划算。",
                        color = DbbColors.Up, fontSize = 12.sp,
                    )
                }
                Spacer(Modifier.height(20.dp))
            }
        }
    }
}

@Composable
private fun BreakdownCard(
    installment: Double,
    term: Int,
    principalPerTerm: Double,
    feePerTerm: Double,
    total: Double,
    principal: Double,
    extra: Double,
) {
    Card(
        Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = DbbColors.Card),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(16.dp),
    ) {
        Column(Modifier.padding(14.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text("每期还款", color = DbbColors.InkSec, fontSize = 12.sp, modifier = Modifier.weight(1f))
                Text(
                    "¥${fmtYuan(installment)} ",
                    color = DbbColors.Ink, fontWeight = FontWeight.Bold, fontSize = 15.sp,
                )
                Text("× $term 期", color = DbbColors.InkTer, fontSize = 11.sp, fontWeight = FontWeight.Medium)
            }
            Spacer(Modifier.height(8.dp))
            Row {
                Text(
                    "本金 ¥${fmtYuan(principalPerTerm)} / 期",
                    color = DbbColors.InkTer, fontSize = 12.sp, modifier = Modifier.weight(1f),
                )
                Text(
                    "手续费 ¥${fmtYuan(feePerTerm)} / 期",
                    color = DbbColors.InkTer, fontSize = 12.sp,
                )
            }
            Spacer(Modifier.height(11.dp))
            Box(Modifier.fillMaxWidth().height(1.dp).background(DbbColors.Border))
            Spacer(Modifier.height(11.dp))
            Row(verticalAlignment = Alignment.Bottom) {
                Text("分期总额", color = DbbColors.InkSec, fontSize = 12.sp, modifier = Modifier.weight(1f))
                Text("¥${fmtYuan(total)}", color = DbbColors.Ink, fontWeight = FontWeight.ExtraBold, fontSize = 18.sp)
            }
            Spacer(Modifier.height(3.dp))
            Row {
                Text(
                    "较全款 ¥${fmtYuan(principal)}",
                    color = DbbColors.InkTer, fontSize = 12.sp, modifier = Modifier.weight(1f),
                )
                Text(
                    "多付 ¥${fmtYuan(extra)}",
                    color = DbbColors.Up, fontWeight = FontWeight.SemiBold, fontSize = 13.sp,
                )
            }
        }
    }
}

@Composable
private fun RateBox(
    title: String,
    value: String,
    sub: String,
    bg: Color,
    fg: Color,
    modifier: Modifier,
) {
    Box(
        modifier
            .clip(RoundedCornerShape(12.dp))
            .background(bg)
            .padding(13.dp),
    ) {
        Column {
            Text(title, color = fg, fontSize = 12.sp, fontWeight = FontWeight.SemiBold)
            Spacer(Modifier.height(2.dp))
            Text(value, color = fg, fontWeight = FontWeight.ExtraBold, fontSize = 20.sp)
            Spacer(Modifier.height(2.dp))
            Text(sub, color = fg.copy(alpha = 0.8f), fontSize = 10.sp)
        }
    }
}

/** 二分法求月 IRR:PV(还款)=principal。sum 关于 r 单调递减,60 次收敛。 */
private fun solveMonthlyIrr(principal: Double, installment: Double, terms: Int): Double {
    var lo = 0.0; var hi = 1.0
    repeat(60) {
        val mid = (lo + hi) / 2
        val sum = (1..terms).sumOf { installment / (1 + mid).pow(it.toDouble()) }
        if (sum > principal) lo = mid else hi = mid
    }
    return (lo + hi) / 2
}

