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

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
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.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.heightIn
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.pager.VerticalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
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.graphics.ColorFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalConfiguration
import com.aiosman.ravenow.GuestLoginCheckOut
import com.aiosman.ravenow.GuestLoginCheckOutScene
import com.aiosman.ravenow.LocalAppTheme
import com.aiosman.ravenow.LocalNavController
import com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.exp.timeAgo
import com.aiosman.ravenow.exp.formatPostTime2
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.rememberDebouncer
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.news.NewsViewModel
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterialApi::class, ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun NewsScreen() {
    val model = NewsViewModel
    val moments = model.moments
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val navController = LocalNavController.current
    val scope = rememberCoroutineScope()
    
    // 评论弹窗状态
    var showCommentModal by remember { mutableStateOf(false) }
    var selectedMoment by remember { mutableStateOf<MomentEntity?>(null) }
    
    // 查看全文弹窗状态
    var showFullArticleModal by remember { mutableStateOf(false) }
    var selectedArticleMoment by remember { mutableStateOf<MomentEntity?>(null) }
    // 垂直翻页状态
    val pagerState = rememberPagerState(pageCount = { moments.size })
    
    // 防抖器
    val likeDebouncer = rememberDebouncer()
    val favoriteDebouncer = rememberDebouncer()

    // 初始化加载数据
    LaunchedEffect(Unit) {
        model.refreshPager()
    }
    
    // 监听数据变化，重置加载状态
    LaunchedEffect(moments.size) {
        // 当数据增加时，如果接近列表末尾，Pager会自动更新页数
    }

    // 当翻页接近末尾时加载更多
    LaunchedEffect(pagerState.currentPage, moments.size) {
        if (moments.isNotEmpty() && pagerState.currentPage >= moments.size - 2) {
            model.loadMore()
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        if (moments.isEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(text = "暂无新闻内容", color = AppColors.text, fontSize = 16.sp)
            }
        } else {
            VerticalPager(
                state = pagerState,
                modifier = Modifier.fillMaxSize()
            ) { page ->
                val momentItem = moments.getOrNull(page) ?: return@VerticalPager
                NewsItem(
                    moment = momentItem,
                    modifier = Modifier.fillMaxSize(),
                    onCommentClick = {
                        selectedMoment = momentItem
                        showCommentModal = true
                    },
                    onReadFullClick = {
                        selectedArticleMoment = momentItem
                        showFullArticleModal = true
                    },
                    onLikeClick = {
                        likeDebouncer {
                            // 检查游客模式
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                navController.navigate(NavigationRoute.Login.route)
                            } else {
                                scope.launch {
                                    if (momentItem.liked) {
                                        model.dislikeMoment(momentItem.id)
                                    } else {
                                        model.likeMoment(momentItem.id)
                                    }
                                }
                            }
                        }
                    },
                    onFavoriteClick = {
                        favoriteDebouncer {
                            // 检查游客模式
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                navController.navigate(NavigationRoute.Login.route)
                            } else {
                                scope.launch {
                                    if (momentItem.isFavorite) {
                                        model.unfavoriteMoment(momentItem.id)
                                    } else {
                                        model.favoriteMoment(momentItem.id)
                                    }
                                }
                            }
                        }
                    }
                )
            }
        }
        
        // 查看全文弹窗
        if (showFullArticleModal && selectedArticleMoment != null) {
            FullArticleModal(
                moment = selectedArticleMoment!!,
                onDismiss = {
                    showFullArticleModal = false
                }
            )
        }
        
        // 评论弹窗
        if (showCommentModal && selectedMoment != null) {
            val configuration = LocalConfiguration.current
            val screenHeight = configuration.screenHeightDp.dp
            // 根据屏幕高度计算最大高度，用于限制弹窗最大高度
            // 小屏幕（< 600dp）：75%，中等屏幕（600-800dp）：70%，大屏幕（> 800dp）：65%
            val maxSheetHeight = when {
                screenHeight.value < 600 -> screenHeight * 0.75f
                screenHeight.value <= 800 -> screenHeight * 0.7f
                else -> screenHeight * 0.65f
            }
            
            val commentSheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            )
            
            // 确保弹窗从下往上展开
            LaunchedEffect(Unit) {
                commentSheetState.expand()
            }
            
            ModalBottomSheet(
                onDismissRequest = {
                    showCommentModal = false
                },
                sheetState = commentSheetState,
                containerColor = AppColors.background,
                shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            ) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(max = maxSheetHeight)
                ) {
                    NewsCommentModal(
                        postId = selectedMoment?.id,
                        commentCount = selectedMoment?.commentCount ?: 0,
                        onDismiss = {
                            showCommentModal = false
                        },
                        onCommentAdded = {
                            selectedMoment?.id?.let { model.onAddComment(it) }
                        },
                        onCommentDeleted = {
                            selectedMoment?.id?.let { model.onDeleteComment(it) }
                        }
                    )
                }
            }
        }
    }
}

//单个新闻项
@Composable
fun NewsItem(
    moment: MomentEntity,
    modifier: Modifier = Modifier,
    onCommentClick: () -> Unit = {},
    onReadFullClick: () -> Unit = {},
    onLikeClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    
    Column(
        modifier = modifier
            .fillMaxSize()
            .background(AppColors.background)
            .padding(vertical = 8.dp),
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column(
            modifier = Modifier
                .weight(1f)
                .padding(bottom = 30.dp)
        ) {
            // 新闻图片
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(300.dp)
                    .padding(horizontal = 16.dp)
            ) {
                if (moment.images.isNotEmpty()) {
                    CustomAsyncImage(
                        context = context,
                        imageUrl = moment.images[0].thumbnail,
                        contentDescription = "新闻图片",
                        contentScale = ContentScale.Crop,
                        blurHash = moment.images[0].blurHash,
                        modifier = Modifier
                            .fillMaxSize()
                            .clip(RoundedCornerShape(8.dp))
                    )
                } else {
                    Image(
                        painter = androidx.compose.ui.res.painterResource(id = R.drawable.default_moment_img),
                        contentDescription = "默认图片",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .fillMaxSize()
                            .clip(RoundedCornerShape(8.dp))
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 新闻标题
            Text(
                text = if (moment.newsTitle.isNotEmpty()) moment.newsTitle else moment.nickname,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = AppColors.text,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 新闻内容（超出使用省略号）
            Text(
                text = com.aiosman.ravenow.utils.Utils.unescapeHtml(
                    if (moment.newsContent.isNotEmpty()) moment.newsContent else (moment.momentTextContent ?: "")
                ),
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                fontSize = 14.sp,
                color = AppColors.text,
                lineHeight = 20.sp,
                maxLines = 6,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 新闻信息
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 16.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // 来源和时间（显示月份与具体时间）
                Text(
                    text = if (moment.newsSource.isNotEmpty()) "${moment.newsSource} • ${moment.time.formatPostTime2()}" else "${moment.nickname} • ${moment.time.formatPostTime2()}",
                    fontSize = 12.sp,
                    color = AppColors.secondaryText,
                    modifier = Modifier
                        .weight(1f)
                        .padding(end = 8.dp),
                    maxLines = 2,
                    overflow = TextOverflow.Ellipsis
                )
                
                // 查看全文
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.noRippleClickable { onReadFullClick() }
                ) {
                    Text(
                        text = stringResource(R.string.read_full_article),
                        fontSize = 13.sp,
                        fontWeight = FontWeight.W600,
                        color = Color(0xFF7c45ed)
                    )
                    Spacer(modifier = Modifier.width(4.dp))
                    Image(
                        painter = androidx.compose.ui.res.painterResource(id = R.mipmap.arrow),
                        contentDescription = "箭头",
                        modifier = Modifier.size(18.dp),
                        colorFilter = ColorFilter.tint(Color(0xFF7c45ed))
                    )
                }
            }
        }

        // 互动栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp)
                .padding(bottom = 25.dp),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            // 点赞
            NewsActionButton(
                icon = if (moment.liked) R.drawable.rider_pro_moment_liked else R.drawable.rider_pro_moment_like,
                count = moment.likeCount.toString(),
                isActive = moment.liked,
                modifier = Modifier.noRippleClickable { onLikeClick() }
            )
            
            // 评论
            NewsActionButton(
                icon = R.mipmap.icon_comment,
                count = moment.commentCount.toString(),
                isActive = false,
                modifier = Modifier.noRippleClickable { onCommentClick() }
            )
            
            // 收藏
            NewsActionButton(
                icon = if (moment.isFavorite) R.mipmap.icon_variant_2 else R.mipmap.icon_collect,
                count = moment.favoriteCount.toString(),
                isActive = false, // 收藏后不使用红色滤镜，保持图标原本颜色
                keepOriginalColor = moment.isFavorite, // 收藏后保持原始颜色
                modifier = Modifier.noRippleClickable { onFavoriteClick() }
            )
            
            // 分享
            NewsActionButton(
                icon = R.mipmap.icon_share,
                count = "",
                isActive = false,
                text = stringResource(R.string.share),
                textSize = 8.sp,
            )
        }
    }
}

// 激活状态的颜色（点赞/收藏时的红色）
private val ActiveIconColor = Color(0xFFD80264)

// 互动栏按钮
@Composable
fun NewsActionButton(
    icon: Int,
    count: String,
    isActive: Boolean,
    modifier: Modifier = Modifier,
    text: String? = null,
    textSize: androidx.compose.ui.unit.TextUnit = 12.sp,
    keepOriginalColor: Boolean = false // 是否保持原始颜色（不应用颜色滤镜）
) {
    val AppColors = LocalAppTheme.current
    
    Row(
        modifier = modifier
            .defaultMinSize(minWidth = 60.dp)
            .background(
                color = AppColors.secondaryBackground,
                shape = RoundedCornerShape(16.dp)
            )
            .padding(horizontal = 12.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Image(
            painter = androidx.compose.ui.res.painterResource(id = icon),
            contentDescription = "操作图标",
            modifier = Modifier.size(16.dp),
            colorFilter = when {
                isActive -> ColorFilter.tint(ActiveIconColor)
                keepOriginalColor -> null // 保持原始颜色
                else -> ColorFilter.tint(AppColors.text) // 未激活状态时使用文字颜色适配暗色模式
            }
        )
        
        if (count.isNotEmpty()) {
            Spacer(modifier = Modifier.width(4.dp))
            Text(
                text = count,
                fontSize = 8.sp,
                fontWeight = FontWeight.Bold,
                color = AppColors.text
            )
        }
        if (text != null) {
            Spacer(modifier = Modifier.width(4.dp))
            Text(
                text = text,
                fontSize = textSize,
                color = AppColors.text,
                fontWeight = FontWeight.Bold
            )
        }
    }
}
