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

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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
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.graphics.RectangleShape
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
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 com.aiosman.ravenow.R
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.ui.comment.CommentModalContent
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.modifiers.noRippleClickable

/**
 * 动态推荐Item组件（post_normal）
 * 参照短视频界面样式，但用图片替代视频播放器
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PostRecommendationItem(
    moment: MomentEntity,
    onLikeClick: ((MomentEntity) -> Unit)? = null,
    onCommentClick: ((MomentEntity) -> Unit)? = null,
    onFavoriteClick: ((MomentEntity) -> Unit)? = null,
    onShareClick: ((MomentEntity) -> Unit)? = null,
    modifier: Modifier = Modifier
) {
    val context = LocalContext.current
    var showCommentModal by remember { mutableStateOf(false) }
    var sheetState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    
    // 图片列表
    val images = moment.images
    val imageCount = images.size
    
    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Color.Black)
    ) {
        // 图片显示区域（替代视频播放器）
        if (imageCount > 0) {
            // 只显示第一张图片，优先使用 thumbnailDirectUrl
            val imageUrl = images[0].thumbnailDirectUrl 
                ?: images[0].directUrl 
                ?: images[0].url
            CustomAsyncImage(
                context = context,
                imageUrl = imageUrl,
                contentDescription = "动态图片",
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop,
                blurHash = images[0].blurHash
            )
        } else {
            // 没有图片时显示默认图片
            Image(
                painter = painterResource(id = R.drawable.default_moment_img),
                contentDescription = "默认图片",
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        }
        
        // 底部左侧：用户信息和文字内容
        Box(
            modifier = Modifier
                .fillMaxSize(),
            contentAlignment = Alignment.BottomStart
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, bottom = 16.dp)
            ) {
                // 用户头像和昵称
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(bottom = 8.dp)
                ) {
                    Box(
                        modifier = Modifier
                            .size(40.dp)
                            .clip(CircleShape)
                            .background(Color.White.copy(alpha = 0.2f))
                    ) {
                        CustomAsyncImage(
                            imageUrl = moment.avatar,
                            contentDescription = "用户头像",
                            modifier = Modifier.fillMaxSize(),
                            defaultRes = R.drawable.default_avatar
                        )
                    }
                    Text(
                        text = "@${moment.nickname}",
                        modifier = Modifier.padding(start = 8.dp),
                        fontSize = 16.sp,
                        color = Color.White,
                        style = TextStyle(fontWeight = FontWeight.Bold)
                    )
                }
                
                // 文字内容
                if (!moment.momentTextContent.isNullOrEmpty()) {
                    Text(
                        modifier = Modifier
                            .fillMaxWidth(0.8f)
                            .padding(top = 4.dp),
                        text = com.aiosman.ravenow.utils.Utils.unescapeHtml(moment.momentTextContent),
                        fontSize = 16.sp,
                        color = Color.White,
                        style = TextStyle(fontWeight = FontWeight.Bold),
                        overflow = TextOverflow.Ellipsis,
                        maxLines = 2
                    )
                }
            }
        }
        
        // 底部右侧：互动按钮
        Box(
            modifier = Modifier
                .fillMaxSize(),
            contentAlignment = Alignment.BottomEnd
        ) {
            Column(
                modifier = Modifier
                    .padding(bottom = 72.dp, end = 12.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                // 用户头像
                UserAvatar(avatarUrl = moment.avatar)
                
                // 点赞
                VideoBtn(
                    icon = if (moment.liked) R.drawable.rider_pro_video_like else R.drawable.rider_pro_video_like,
                    text = formatCount(moment.likeCount)
                ) {
                    onLikeClick?.invoke(moment)
                }
                
                // 评论
                VideoBtn(
                    icon = R.drawable.rider_pro_video_comment,
                    text = formatCount(moment.commentCount)
                ) {
                    showCommentModal = true
                    onCommentClick?.invoke(moment)
                }
                
                // 收藏
                VideoBtn(
                    icon = R.drawable.rider_pro_video_favor,
                    text = formatCount(moment.favoriteCount)
                ) {
                    onFavoriteClick?.invoke(moment)
                }
                
                // 分享
                VideoBtn(
                    icon = R.drawable.rider_pro_video_share,
                    text = formatCount(moment.shareCount)
                ) {
                    onShareClick?.invoke(moment)
                }
            }
        }
    }
    
    // 评论弹窗
    if (showCommentModal) {
        ModalBottomSheet(
            onDismissRequest = { showCommentModal = false },
            containerColor = Color.White,
            sheetState = sheetState
        ) {
            CommentModalContent(postId = moment.id) {
                // 评论添加后的回调
            }
        }
    }
}

@Composable
private fun UserAvatar(avatarUrl: String? = null) {
    Box(
        modifier = Modifier
            .padding(bottom = 16.dp)
            .size(40.dp)
            .clip(CircleShape)
            .background(Color.White.copy(alpha = 0.2f))
    ) {
        if (avatarUrl != null && avatarUrl.isNotEmpty()) {
            CustomAsyncImage(
                imageUrl = avatarUrl,
                contentDescription = "用户头像",
                modifier = Modifier.fillMaxSize(),
                defaultRes = R.drawable.default_avatar
            )
        } else {
            Image(
                painter = painterResource(id = R.drawable.default_avatar),
                contentDescription = "用户头像"
            )
        }
    }
}

// 格式化数字显示
private fun formatCount(count: Int): String {
    return when {
        count >= 1_000_000 -> String.format("%.1fM", count / 1_000_000.0)
        count >= 1_000 -> String.format("%.1fK", count / 1_000.0)
        else -> count.toString()
    }
}

@Composable
private fun VideoBtn(
    icon: Int,
    text: String,
    onClick: (() -> Unit)? = null
) {
    Column(
        modifier = Modifier
            .padding(bottom = 16.dp)
            .noRippleClickable {
                onClick?.invoke()
            },
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            modifier = Modifier.size(36.dp),
            painter = painterResource(id = icon),
            contentDescription = ""
        )
        Text(
            text = text,
            fontSize = 11.sp,
            color = Color.White,
            style = TextStyle(fontWeight = FontWeight.Bold)
        )
    }
}

