package com.jishisongfu.duobibi.ui.records

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Search
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.FloatingActionButton
import androidx.compose.material3.Icon
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.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.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.jishisongfu.duobibi.ui.DbbProgressBar
import com.jishisongfu.duobibi.ui.PlatformAvatar
import com.jishisongfu.duobibi.ui.ProductThumb
import com.jishisongfu.duobibi.ui.TagChip
import com.jishisongfu.duobibi.ui.fmtYuan
import com.jishisongfu.duobibi.ui.theme.DbbColors
import com.jishisongfu.duobibi.util.ClusterStats
import com.jishisongfu.duobibi.util.OverallStats

private enum class RecordsSort(val label: String) {
    RECENT("最近"), SPREAD("价差大"), MIN_PRICE("价最低")
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecordsScreen(
    onOpenCluster: (Long) -> Unit,
    onAdd: () -> Unit,
    vm: RecordsViewModel = hiltViewModel(),
) {
    val groups by vm.groups.collectAsStateWithLifecycle()
    val query by vm.query.collectAsStateWithLifecycle()
    val overall by vm.overall.collectAsStateWithLifecycle()
    // RecordsSort 是 enum,Java Enum 默认 Serializable,rememberSaveable autoSaver 直接吃。
    var sort by rememberSaveable { mutableStateOf(RecordsSort.RECENT) }

    val sorted = remember(groups, sort) {
        when (sort) {
            RecordsSort.RECENT -> groups
            RecordsSort.SPREAD -> groups.sortedByDescending { it.maxPrice - it.minPrice }
            RecordsSort.MIN_PRICE -> groups.sortedBy { it.minPrice }
        }
    }

    Scaffold(
        containerColor = DbbColors.Bg,
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        "我的记录",
                        fontWeight = FontWeight.ExtraBold,
                        fontSize = 20.sp,
                        color = DbbColors.Ink,
                    )
                },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = DbbColors.Card),
            )
        },
        floatingActionButton = {
            FloatingActionButton(
                onClick = onAdd,
                containerColor = DbbColors.Teal,
                contentColor = Color.White,
                shape = RoundedCornerShape(18.dp),
            ) {
                Icon(Icons.Filled.Add, "手动记一笔")
            }
        },
    ) { padding ->
        Column(
            Modifier
                .padding(padding)
                .fillMaxSize()
                .background(DbbColors.Bg),
        ) {
            if (sorted.isEmpty() && query.isBlank() && (overall?.totalRecords ?: 0) == 0) {
                EmptyHint()
            } else {
                LazyColumn(
                    Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(14.dp, 10.dp, 14.dp, 96.dp),
                    verticalArrangement = Arrangement.spacedBy(9.dp),
                ) {
                    item {
                        overall?.let { StatsBlock(it) }
                    }
                    if (overall?.topSpread?.isNotEmpty() == true) {
                        item { SpreadRankCard(overall!!.topSpread) }
                    }
                    item {
                        SearchAndFilter(
                            query = query,
                            onQuery = vm::setQuery,
                            sort = sort,
                            onSort = { sort = it },
                            groupCount = sorted.size,
                        )
                    }
                    if (sorted.isEmpty()) {
                        item {
                            Box(
                                Modifier.fillMaxWidth().padding(top = 32.dp),
                                contentAlignment = Alignment.Center,
                            ) {
                                Text(
                                    "没找到匹配的商品",
                                    color = DbbColors.InkTer, fontSize = 13.sp,
                                )
                            }
                        }
                    } else {
                        items(sorted, key = { it.clusterId }) { g ->
                            ProductCard(g) { onOpenCluster(g.clusterId) }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun EmptyHint() {
    Box(
        Modifier.fillMaxSize().padding(32.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            "还没有记录。\n在购物 App 点蓝色浮窗、用截图记账,或点右下 + 手动记一笔。",
            color = DbbColors.InkTer, fontSize = 13.sp, textAlign = TextAlign.Center,
        )
    }
}

@Composable
private fun StatsBlock(overall: OverallStats) {
    Column {
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            StatBox(overall.totalProducts.toString(), "商品", Modifier.weight(1f), alt = false)
            StatBox(overall.totalRecords.toString(), "记录", Modifier.weight(1f), alt = false)
            StatBox(fmtYuan(overall.totalSaved), "已省¥", Modifier.weight(1f), alt = false)
        }
        Spacer(Modifier.height(8.dp))
        Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
            StatBox(overall.totalPlatforms.toString(), "覆盖平台", Modifier.weight(1f), alt = true)
            StatBox(overall.recordsToday.toString(), "今日记录", Modifier.weight(1f), alt = true)
            StatBox(fmtYuan(overall.avgSavePerProduct), "件均省¥", Modifier.weight(1f), alt = true)
        }
    }
}

@Composable
private fun StatBox(value: String, label: String, modifier: Modifier, alt: Boolean) {
    // 两行统计盒都走 teal 家族,深浅区分,不再用 sky 增添第二个色相。
    val bg = if (alt) Color(0xFFECFAF9) else DbbColors.TealBg
    Box(
        modifier.clip(RoundedCornerShape(14.dp)).background(bg).padding(vertical = 11.dp),
        contentAlignment = Alignment.Center,
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            Text(value, fontWeight = FontWeight.ExtraBold, fontSize = 18.sp, color = DbbColors.TealDark)
            Text(label, fontSize = 11.sp, color = DbbColors.InkSec)
        }
    }
}

@Composable
private fun SpreadRankCard(top: List<ClusterStats>) {
    val maxSpread = top.maxOfOrNull { it.priceSpread } ?: 1.0
    Card(
        Modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(containerColor = DbbColors.Card),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(16.dp),
    ) {
        Column(Modifier.padding(horizontal = 14.dp, vertical = 12.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Text(
                    "💰 价差榜",
                    color = DbbColors.Ink, fontWeight = FontWeight.Bold, fontSize = 13.sp,
                )
                Spacer(Modifier.weight(1f))
                Text("同款跨平台最大差价", color = DbbColors.InkTer, fontSize = 11.sp)
            }
            Spacer(Modifier.height(8.dp))
            top.take(3).forEachIndexed { i, c ->
                if (i > 0) Spacer(Modifier.height(6.dp))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text(
                        c.title,
                        color = DbbColors.Ink, fontSize = 12.sp,
                        maxLines = 1, overflow = TextOverflow.Ellipsis,
                        modifier = Modifier.width(128.dp),
                    )
                    Spacer(Modifier.width(8.dp))
                    DbbProgressBar(
                        fraction = (c.priceSpread / maxSpread).toFloat(),
                        color = DbbColors.Teal,
                        modifier = Modifier.weight(1f),
                    )
                    Spacer(Modifier.width(8.dp))
                    Text(
                        "¥${fmtYuan(c.priceSpread)}",
                        color = DbbColors.Save,
                        fontWeight = FontWeight.SemiBold,
                        fontSize = 12.sp,
                        modifier = Modifier.width(48.dp),
                        textAlign = TextAlign.End,
                    )
                }
            }
        }
    }
}

@Composable
private fun SearchAndFilter(
    query: String,
    onQuery: (String) -> Unit,
    sort: RecordsSort,
    onSort: (RecordsSort) -> Unit,
    groupCount: Int,
) {
    Column {
        OutlinedTextField(
            value = query, onValueChange = onQuery,
            modifier = Modifier.fillMaxWidth(),
            placeholder = { Text("搜商品名", color = DbbColors.InkTer) },
            leadingIcon = { Icon(Icons.Filled.Search, null, tint = DbbColors.InkTer) },
            singleLine = true,
            shape = RoundedCornerShape(14.dp),
        )
        Spacer(Modifier.height(8.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            RecordsSort.entries.forEach { s ->
                SortChip(s.label, selected = s == sort) { onSort(s) }
                Spacer(Modifier.width(6.dp))
            }
            Spacer(Modifier.weight(1f))
            Text("共 $groupCount 个商品组", color = DbbColors.InkTer, fontSize = 11.sp)
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SortChip(label: String, selected: Boolean, onClick: () -> Unit) {
    FilterChip(
        selected = selected,
        onClick = onClick,
        label = { Text(label, fontSize = 12.sp) },
        colors = FilterChipDefaults.filterChipColors(
            selectedContainerColor = DbbColors.Teal,
            selectedLabelColor = Color.White,
        ),
    )
}

@Composable
private fun ProductCard(g: ProductGroup, onClick: () -> Unit) {
    val spread = g.maxPrice - g.minPrice
    Card(
        Modifier.fillMaxWidth().clickable(onClick = onClick),
        colors = CardDefaults.cardColors(containerColor = DbbColors.Card),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(16.dp),
    ) {
        Column(Modifier.padding(horizontal = 12.dp, vertical = 11.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                ProductThumb(title = g.title, size = 38.dp)
                Spacer(Modifier.width(10.dp))
                Text(
                    g.title,
                    fontWeight = FontWeight.Bold,
                    color = DbbColors.Ink,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                    modifier = Modifier.weight(1f),
                )
                Spacer(Modifier.width(6.dp))
                Text("近期", color = DbbColors.InkTer, fontSize = 10.sp)
            }
            Spacer(Modifier.height(6.dp))
            Row(verticalAlignment = Alignment.Bottom) {
                PlatformAvatar(g.minSourceApp, small = true)
                Spacer(Modifier.width(5.dp))
                Text("最低 ", color = DbbColors.InkSec, fontSize = 12.sp)
                Text(
                    "¥${fmtYuan(g.minPrice)}",
                    color = DbbColors.Teal,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 18.sp,
                )
                Text("  ${g.minSourceApp}", color = DbbColors.InkTer, fontSize = 11.sp)
                Spacer(Modifier.weight(1f))
                if (g.typicalPrice != null) {
                    Text(
                        "常见 ¥${fmtYuan(g.typicalPrice)}",
                        color = DbbColors.InkTer,
                        fontSize = 11.sp,
                    )
                }
                if (spread > 0) {
                    Spacer(Modifier.width(6.dp))
                    TagChip("差 ¥${fmtYuan(spread)}", bg = DbbColors.SaveBg, fg = DbbColors.Save)
                }
            }
            Spacer(Modifier.height(8.dp))
            Row(verticalAlignment = Alignment.CenterVertically) {
                g.sources.take(6).forEach { p ->
                    PlatformAvatar(p, small = true)
                    Spacer(Modifier.width(5.dp))
                }
                Spacer(Modifier.weight(1f))
                Text(
                    "${g.recordCount} 条记录 · ${g.sources.size} 平台",
                    color = DbbColors.InkTer, fontSize = 11.sp,
                )
            }
        }
    }
}
