package com.aiosman.ravenow.ui.index.tabs.moment.tabs.hot

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.lazy.staggeredgrid.rememberLazyStaggeredGridState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import kotlinx.coroutines.flow.collectLatest
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.runtime.collectAsState
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.search.SearchViewModel
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.navigateToPost

/**
 * 动态列表
 */
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun HotMomentsList() {
    val model = HotMomentViewModel
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 48.dp
    val isRefreshing by model.isRefreshing.collectAsState()
    
    LaunchedEffect(Unit) {
        model.loadMoments()
    }
    
    val state = rememberPullRefreshState(isRefreshing, onRefresh = {
        model.refreshMoments()
    })

    Column(
        modifier = Modifier
            .fillMaxSize()
            .pullRefresh(state)

    ) {
        Column(
            modifier = Modifier.fillMaxWidth().background(
                AppColors.background).padding(bottom = 0.dp)
        ) {
        }

        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
                .padding(2.dp)
        ) {
            DiscoverView()
            PullRefreshIndicator(isRefreshing, state, Modifier.align(Alignment.TopCenter))
        }
    }
}


@Composable
fun DiscoverView() {
    val model = HotMomentViewModel
    val moments by model.discoverMoments.collectAsState()
    val isLoading by model.isLoading.collectAsState()
    val context = LocalContext.current
    val navController = LocalNavController.current
    val gridState = rememberLazyStaggeredGridState()
    val AppColors = LocalAppTheme.current
    // 监听滚动到底部，自动加载更多
    LaunchedEffect(gridState, moments.size) {
        snapshotFlow {
            val layoutInfo = gridState.layoutInfo
            val visibleItemsInfo = layoutInfo.visibleItemsInfo
            if (visibleItemsInfo.isNotEmpty() && moments.isNotEmpty()) {
                val lastVisibleItemIndex = visibleItemsInfo.lastOrNull()?.index ?: 0
                lastVisibleItemIndex >= moments.size - 6 // 距离底部还有6个项目时开始加载
            } else {
                false
            }
        }.collectLatest { shouldLoadMore ->
            if (shouldLoadMore && !isLoading) {
                model.loadMoments()
            }
        }
    }
    
    LazyVerticalStaggeredGrid(
        columns =  StaggeredGridCells.Fixed(2),
        state = gridState,
        modifier = Modifier.fillMaxSize().padding(bottom = 8.dp),
        contentPadding = androidx.compose.foundation.layout.PaddingValues(horizontal = 8.dp, vertical = 4.dp)
    ) {
        items(moments) { momentItem ->
            // 如果图片列表为空，跳过这个 item
            if (momentItem.images.isEmpty()) {
                return@items
            }
            
            val debouncer = rememberDebouncer()

            val textContent = momentItem.momentTextContent
            // 对于英文和日文，每行字符数会更少，使用更保守的估算
            val estimatedCharsPerLine = if (!textContent.isNullOrEmpty()) {
                // 检测是否包含非中文字符（英文、日文等）
                val hasNonChinese = textContent?.any { 
                    val code = it.code
                    !(code >= 0x4E00 && code <= 0x9FFF) // 不在中文字符范围内
                } ?: false
                if (hasNonChinese) 15 else 20 // 英文/日文每行更少字符
            } else {
                20
            }
            val textLines = if (!textContent.isNullOrEmpty()) {
                val estimatedLines = ((textContent?.length ?: 0) / estimatedCharsPerLine) + 1
                minOf(estimatedLines, 2) // 最多2行
            } else {
                0
            }

            val baseHeight = 200.dp
            val singleLineTextHeight = 24.dp // 增加高度以适应英文/日文
            val doubleLineTextHeight = 44.dp // 增加高度以适应英文/日文
            val authorInfoHeight = 25.dp
            val paddingHeight = 10.dp
            val paddingHeight2 = 3.dp
            val totalHeight = baseHeight + when (textLines) {
                0 -> authorInfoHeight + paddingHeight
                1 -> singleLineTextHeight + authorInfoHeight + paddingHeight
                else -> doubleLineTextHeight + authorInfoHeight + paddingHeight2
            }
            
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(2.dp)
                    .noRippleClickable {
                        debouncer {
                            navController.navigateToPost(
                                id = momentItem.id,
                                highlightCommentId = 0,
                                initImagePagerIndex = 0
                            )
                        }
                    }
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .background(AppColors.secondaryBackground, RoundedCornerShape(12.dp))
                ) {
                    CustomAsyncImage(
                        imageUrl = momentItem.images[0].thumbnail,
                        contentDescription = "",
                        modifier = Modifier
                            .fillMaxWidth()
                            .height(baseHeight)
                            .clip(RoundedCornerShape(
                                topStart = 12.dp,
                                topEnd = 12.dp,
                                bottomStart = 0.dp,
                                bottomEnd = 0.dp)),
                        context = context,
                        showShimmer = true
                    )

                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(horizontal = 8.dp, vertical = 8.dp)
                    ) {
                        // 文本内容区域，限制最大高度
                        if (!momentItem.momentTextContent.isNullOrEmpty()) {
                            androidx.compose.material3.Text(
                                text = com.aiosman.ravenow.utils.Utils.unescapeHtml(momentItem.momentTextContent),
                                modifier = Modifier.fillMaxWidth(),
                                fontSize = 12.sp,
                                color = AppColors.text,
                                maxLines = 2,
                                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
                                lineHeight = 16.sp // 设置行高以适应不同语言
                            )
                        }

                        // 使用 Spacer 确保头像昵称栏始终在底部，有足够的空间
                        Spacer(modifier = Modifier.weight(1f))

                        // 头像昵称栏，确保始终完整显示，设置最小高度避免被挤压
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .heightIn(min = 25.dp) // 最小高度确保完整显示，自适应避免被挤压
                                .padding(top = 5.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            CustomAsyncImage(
                                imageUrl = momentItem.avatar,
                                contentDescription = "",
                                modifier = Modifier
                                    .size(16.dp)
                                    .clip(RoundedCornerShape(8.dp)),
                                context = context,
                                showShimmer = true
                            )

                            androidx.compose.material3.Text(
                                text = momentItem.nickname,
                                modifier = Modifier
                                    .padding(start = 4.dp)
                                    .weight(1f),
                                fontSize = 11.sp,
                                color = AppColors.text.copy(alpha = 0.6f),
                                maxLines = 1,
                                overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
                            )
                        }
                    }
                }
                if (momentItem.images.size > 1) {
                    Box(
                        modifier = Modifier
                            .padding(top = 8.dp, end = 8.dp)
                            .align(Alignment.TopEnd)
                    ) {
                        Image(
                            modifier = Modifier.size(24.dp),
                            painter = painterResource(R.drawable.rider_pro_picture_more),
                            contentDescription = "",
                        )
                    }
                }


            }

        }
    }
}