package com.jishisongfu.duobibi.ui.tools

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.padding
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.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
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.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
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.Modifier
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.abs

private enum class PriceUnit(val label: String, val factor: Double, val piece: Boolean, val base: String) {
    G("克", 1.0, false, "100g"), KG("千克", 1000.0, false, "100g"),
    ML("毫升", 1.0, false, "100ml"), L("升", 1000.0, false, "100ml"),
    PIECE("件", 1.0, true, "件"),
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun UnitPriceCalculatorScreen(onBack: () -> Unit) {
    // PriceUnit 是 enum,Java Enum 默认 Serializable。
    var unit by rememberSaveable { mutableStateOf(PriceUnit.G) }
    var pa by rememberSaveable { mutableStateOf("") }
    var qa by rememberSaveable { mutableStateOf("") }
    var pb by rememberSaveable { mutableStateOf("") }
    var qb by rememberSaveable { mutableStateOf("") }

    Scaffold(topBar = { CalcBar("单价对比", onBack) }) { padding ->
        Column(
            Modifier.padding(padding).fillMaxSize().background(MaterialTheme.colorScheme.background)
                .verticalScroll(rememberScrollState()).padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            Text("选规格单位", color = DbbColors.InkSec, fontSize = 12.sp)
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                PriceUnit.entries.forEach { u ->
                    FilterChip(selected = unit == u, onClick = { unit = u }, label = { Text(u.label) },
                        colors = FilterChipDefaults.filterChipColors(selectedContainerColor = DbbColors.Teal, selectedLabelColor = Color.White))
                }
            }
            ItemInput("商品 A", pa, qa, unit.label, { pa = it.numeric() }, { qa = it.numeric() })
            ItemInput("商品 B", pb, qb, unit.label, { pb = it.numeric() }, { qb = it.numeric() })

            val upa = unitPrice(pa.toDoubleOrNull(), qa.toDoubleOrNull(), unit)
            val upb = unitPrice(pb.toDoubleOrNull(), qb.toDoubleOrNull(), unit)
            if (upa != null && upb != null) {
                val cheaperA = upa < upb
                val saved = abs(upa - upb)
                val pct = (saved / maxOf(upa, upb) * 100).toInt()
                Card(
                    Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = DbbColors.SaveBg),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), shape = RoundedCornerShape(14.dp),
                ) {
                    Column(Modifier.padding(16.dp)) {
                        Text("每${unit.base}单价", color = DbbColors.InkSec, fontSize = 12.sp)
                        Spacer(Modifier.padding(2.dp))
                        Text("A ¥${fmtYuan(upa)}   B ¥${fmtYuan(upb)}", fontWeight = FontWeight.Bold, color = DbbColors.Ink)
                        Spacer(Modifier.padding(4.dp))
                        Text("👉 ${if (cheaperA) "商品 A" else "商品 B"} 更划算,每${unit.base}便宜 ¥${fmtYuan(saved)}(约 $pct%)",
                            color = DbbColors.Save, fontWeight = FontWeight.SemiBold)
                    }
                }
            }
        }
    }
}

private fun unitPrice(price: Double?, qty: Double?, u: PriceUnit): Double? {
    if (price == null || qty == null || price <= 0 || qty <= 0) return null
    val baseQty = qty * u.factor
    return if (u.piece) price / baseQty else price / baseQty * 100
}

@Composable
private fun ItemInput(
    name: String,
    price: String,
    qty: String,
    unitLabel: String,
    onP: (String) -> Unit,
    onQ: (String) -> Unit,
) {
    Card(
        Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = DbbColors.Card),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp), shape = RoundedCornerShape(14.dp),
    ) {
        Column(Modifier.padding(14.dp)) {
            Text(name, fontWeight = FontWeight.Bold, color = DbbColors.Ink)
            Spacer(Modifier.padding(4.dp))
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                OutlinedTextField(value = price, onValueChange = onP, label = { Text("价格(元)") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), singleLine = true, modifier = Modifier.weight(1f))
                OutlinedTextField(value = qty, onValueChange = onQ, label = { Text("规格($unitLabel)") },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal), singleLine = true, modifier = Modifier.weight(1f))
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun CalcBar(title: String, onBack: () -> Unit) {
    TopAppBar(
        title = { Text(title, fontWeight = FontWeight.Bold, color = DbbColors.Ink) },
        navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回", tint = DbbColors.Ink) } },
        colors = TopAppBarDefaults.topAppBarColors(containerColor = DbbColors.Card),
    )
}

internal fun String.numeric(): String = filter { it.isDigit() || it == '.' }
