package com.jishisongfu.duobibi.ui.watched

import androidx.compose.foundation.background
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.WindowInsets
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.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
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.clip
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.jishisongfu.duobibi.ui.discover.DISCOVER_SEED
import com.jishisongfu.duobibi.ui.discover.PriceCompareCard
import com.jishisongfu.duobibi.ui.theme.DbbColors
import com.jishisongfu.duobibi.ui.theme.DbbGradients
import com.jishisongfu.duobibi.util.WatchedPrefs

/**
 * 关注的商品列表 —— 从发现页 hero ❤️ 入口进入。
 *
 * 跟"降价雷达"语义区分:
 *  - **关注**:用户主动点 ❤️ 收藏的商品(只看价格走势,不要求设心理价 / 触发提醒)
 *  - **雷达**:主动设了心理价的监控(降到价就触发 push 提醒)
 *  关注更轻、零设置;雷达更重、有目标价。
 *
 * 数据源是 [WatchedPrefs.watchedFlow] 反应式订阅 SharedPreferences 里的 id Set,
 * 再查 [DISCOVER_SEED] 还原 DiscoverItem。后续上自定义关注(非种子内)再迁 Room。
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun WatchedProductsScreen(
    onBack: () -> Unit,
    onOpenDetail: (itemId: String) -> Unit,
) {
    val ctx = LocalContext.current
    val watchedFlow = remember { WatchedPrefs.watchedFlow(ctx) }
    val watchedIds by watchedFlow.collectAsStateWithLifecycle(initialValue = WatchedPrefs.watchedIds(ctx))
    val items = remember(watchedIds) {
        // 保留原 DISCOVER_SEED 顺序,只筛 watchedIds 里的
        DISCOVER_SEED.filter { it.id in watchedIds }
    }

    Scaffold(
        containerColor = DbbColors.Bg,
        contentWindowInsets = WindowInsets(0),
    ) { padding ->
        Column(
            Modifier.padding(padding).fillMaxSize().background(DbbColors.Bg),
        ) {
            WatchedHero(count = items.size, onBack = onBack)
            if (items.isEmpty()) {
                EmptyHint()
            } else {
                LazyVerticalStaggeredGrid(
                    columns = StaggeredGridCells.Fixed(2),
                    modifier = Modifier.fillMaxSize(),
                    contentPadding = PaddingValues(10.dp, 10.dp, 10.dp, 24.dp),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalItemSpacing = 8.dp,
                ) {
                    items(items, key = { it.id }) { item ->
                        PriceCompareCard(
                            item = item,
                            isWatched = true,
                            onClick = { onOpenDetail(item.id) },
                            onToggleWatch = { WatchedPrefs.toggle(ctx, item.id) },
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun WatchedHero(count: Int, onBack: () -> Unit) {
    Box(
        Modifier
            .fillMaxWidth()
            .background(Brush.verticalGradient(DbbGradients.Watched))
            .windowInsetsPadding(WindowInsets.statusBars),
    ) {
        Row(
            Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 14.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(onClick = onBack, modifier = Modifier.size(40.dp)) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回", tint = Color.White)
            }
            Spacer(Modifier.size(4.dp))
            Box(
                Modifier
                    .size(44.dp)
                    .clip(RoundedCornerShape(14.dp))
                    .background(Color.White.copy(alpha = 0.22f)),
                contentAlignment = Alignment.Center,
            ) {
                Icon(Icons.Filled.Favorite, contentDescription = null, tint = Color.White, modifier = Modifier.size(24.dp))
            }
            Spacer(Modifier.size(12.dp))
            Column(Modifier.weight(1f)) {
                Text(
                    "我的关注",
                    color = Color.White,
                    fontWeight = FontWeight.ExtraBold,
                    fontSize = 20.sp,
                )
                Text(
                    if (count > 0) "$count 件商品在关注中" else "还没关注任何商品",
                    color = Color.White.copy(alpha = 0.88f),
                    fontSize = 12.sp,
                )
            }
        }
    }
}

@Composable
private fun EmptyHint() {
    Column(
        Modifier.fillMaxSize().padding(40.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Box(
            Modifier
                .size(76.dp)
                .clip(CircleShape)
                .background(DbbColors.RoseBg),
            contentAlignment = Alignment.Center,
        ) {
            Icon(
                Icons.Filled.Favorite,
                contentDescription = null,
                tint = DbbColors.Rose,
                modifier = Modifier.size(36.dp),
            )
        }
        Spacer(Modifier.height(14.dp))
        Text("还没关注任何商品", color = DbbColors.Ink, fontWeight = FontWeight.Bold, fontSize = 15.sp)
        Spacer(Modifier.height(6.dp))
        Text(
            "去「发现」逛逛,点商品卡右上角的 ❤️ 把它收藏到这里",
            color = DbbColors.InkTer,
            fontSize = 12.sp,
            textAlign = TextAlign.Center,
        )
    }
}
