package com.aiosman.ravenow.ui.post

import android.util.Log
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.interaction.MutableInteractionSource
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.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.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.LinearProgressIndicator
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
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.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.buildAnnotatedString
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.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ConstVars
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.data.CommonService
import com.aiosman.ravenow.data.CommonServiceImpl
import com.aiosman.ravenow.data.DictService
import com.aiosman.ravenow.data.DictServiceImpl
import com.aiosman.ravenow.data.ReportReasonList
import com.aiosman.ravenow.entity.CommentEntity
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentImageEntity
import com.aiosman.ravenow.entity.ReportReasons
import com.aiosman.ravenow.exp.formatPostTime
import com.aiosman.ravenow.exp.timeAgo
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.comment.NoticeScreenHeader
import com.aiosman.ravenow.ui.composables.ActionButton
import com.aiosman.ravenow.ui.composables.AnimatedFavouriteIcon
import com.aiosman.ravenow.ui.composables.AnimatedLikeIcon
import com.aiosman.ravenow.ui.composables.BottomNavigationPlaceholder
import com.aiosman.ravenow.ui.composables.CustomAsyncImage
import com.aiosman.ravenow.ui.composables.CustomClickableText
import com.aiosman.ravenow.ui.composables.EditCommentBottomModal
import com.aiosman.ravenow.ui.composables.FollowButton
import com.aiosman.ravenow.ui.composables.StatusBarSpacer
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.composables.debouncedClickable
import com.aiosman.ravenow.ui.composables.rememberDebouncedNavigation
import com.aiosman.ravenow.utils.FileUtil.saveImageToGallery
import com.google.gson.Gson
import kotlinx.coroutines.launch
import net.engawapg.lib.zoomable.rememberZoomState
import net.engawapg.lib.zoomable.zoomable

/**
 * 动态详情
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PostScreen(
    id: String,
    highlightCommentId: Int?,
    initImagePagerIndex: Int?
) {
    val viewModel = viewModel<PostViewModel>(
        key = "PostViewModel_$id",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                Log.d("PostViewModel", "Create PostViewModel with id: $id")
                return PostViewModel(id) as T
            }
        }
    )
    val commentsViewModel = viewModel.commentsViewModel
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()
    var showCommentMenu by remember { mutableStateOf(false) }
    var contextComment by remember { mutableStateOf<CommentEntity?>(null) }
    var replyComment by remember { mutableStateOf<CommentEntity?>(null) }
    var showCommentModal by remember { mutableStateOf(false) }
    var commentModalState = rememberModalBottomSheetState(skipPartiallyExpanded = true)
    var editCommentModalState = rememberModalBottomSheetState(
        skipPartiallyExpanded = true
    )
    var showReportDialog by remember { mutableStateOf(false) }
    val AppColors = LocalAppTheme.current

    LaunchedEffect(Unit) {
        viewModel.initData(
            highlightCommentId = highlightCommentId.let {
                if (it == 0) null else it
            }
        )
    }

    if (showCommentMenu) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentMenu = false
            },
            containerColor = AppColors.background,
            sheetState = commentModalState,
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        ) {
            CommentMenuModal(
                onDeleteClick = {
                    scope.launch {
                        commentModalState.hide()
                        showCommentMenu = false
                    }
                    contextComment?.let {
                        viewModel.deleteComment(it.id)
                    }
                },
                commentEntity = contextComment,
                onCloseClick = {
                    scope.launch {
                        commentModalState.hide()
                        showCommentMenu = false
                    }
                },
                isSelf = AppState.UserId?.toLong() == contextComment?.author,
                onLikeClick = {
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                        scope.launch {
                            commentModalState.hide()
                            showCommentMenu = false
                        }
                        debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                    } else {
                        scope.launch {
                            commentModalState.hide()
                            showCommentMenu = false
                        }
                        contextComment?.let {
                            // 防抖机制已在ViewModel中实现
                            viewModel.viewModelScope.launch {
                                if (it.liked) {
                                    viewModel.unlikeComment(it.id)
                                } else {
                                    viewModel.likeComment(it.id)
                                }
                            }
                        }
                    }

                },
                onReplyClick = {
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                        scope.launch {
                            commentModalState.hide()
                            showCommentMenu = false
                        }
                        debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                    } else {
                        scope.launch {
                            commentModalState.hide()
                            showCommentMenu = false
                            replyComment = contextComment
                            showCommentModal = true
                        }
                    }
                }
            )
        }
    }
    if (showCommentModal) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentModal = false
            },
            containerColor = AppColors.background,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        ) {
            EditCommentBottomModal(replyComment) {
                viewModel.viewModelScope.launch {
                    if (replyComment != null) {
                        if (replyComment?.parentCommentId != null) {
                            // 第三级评论
                            viewModel.createComment(
                                content = it,
                                parentCommentId = replyComment?.parentCommentId,
                                replyUserId = replyComment?.author?.toInt(),
                                replyCommentId = replyComment?.id
                            )
                        } else {
                            // 子级评论
                            viewModel.createComment(
                                content = it,
                                parentCommentId = replyComment?.id,
                                replyCommentId = replyComment?.id
                            )
                        }
                    } else {
                        // 顶级评论
                        viewModel.createComment(
                            content = it
                        )
                    }

                    editCommentModalState.hide()
                    showCommentModal = false
                }

            }
        }
    }
    if (showReportDialog && viewModel.moment != null) {
        ModalBottomSheet(
            onDismissRequest = {
                showReportDialog = false
            },
            containerColor = AppColors.background,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),

        ) {
            ReportModal(
                momentId = viewModel.moment!!.id,
                onClose = {
                    showReportDialog = false
                }
            )
        }
    }
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            if (!viewModel.isError) {
                PostBottomBar(
                    onLikeClick = {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                            debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                        } else {
                            scope.launch {
                                if (viewModel.moment?.liked == true) {
                                    viewModel.dislikeMoment()
                                } else {
                                    viewModel.likeMoment()
                                }
                            }
                        }
                    },
                    onCreateCommentClick = {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                            debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                        } else {
                            replyComment = null
                            showCommentModal = true
                        }
                    },
                    onFavoriteClick = {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                            debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                        } else {
                            scope.launch {
                                if (viewModel.moment?.isFavorite == true) {
                                    viewModel.unfavoriteMoment()
                                } else {
                                    viewModel.favoriteMoment()
                                }
                            }
                        }
                    },
                    momentEntity = viewModel.moment
                )
            }
        }
    ) {
        it
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(AppColors.background)
        ) {
            StatusBarSpacer()
            if (viewModel.isError) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp)
                ) {
                    NoticeScreenHeader("Post", moreIcon = false)
                }

                Box(
                    modifier = Modifier
                        .fillMaxSize(),
                    contentAlignment = Alignment.Center
                ) {
                    Text(
                        text = "Umm, post are not found.",
                        style = TextStyle(
                            fontWeight = FontWeight.Bold,
                            fontSize = 16.sp
                        ),
                        color = AppColors.text
                    )
                }
            } else {
                Header(
                    avatar = viewModel.avatar,
                    nickname = viewModel.nickname,
                    userId = viewModel.moment?.authorId,
                    isFollowing = viewModel.moment?.followStatus == true,
                    onFollowClick = {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.FOLLOW_USER)) {
                            debouncedNavigation {
                                navController.navigate(NavigationRoute.Login.route)
                            }
                        } else {
                            scope.launch {
                                if (viewModel.moment?.followStatus == true) {
                                    viewModel.unfollowUser()
                                } else {
                                    viewModel.followUser()
                                }
                            }
                        }
                    },
                    onDeleteClick = {
                        viewModel.deleteMoment {
                            debouncedNavigation {
                                navController.navigateUp()
                            }
                        }
                    },
                    onReportClick = {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.REPORT_CONTENT)) {
                            debouncedNavigation {
                                navController.navigate(NavigationRoute.Login.route)
                            }
                        } else {
                            showReportDialog = true
                        }
                    }
                )

                LazyColumn(
                    modifier = Modifier
                        .fillMaxWidth()
                        .weight(1f)
                        .animateContentSize(
                            animationSpec = tween(
                                durationMillis = 500
                            )
                        )
                ) {
                    item {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .aspectRatio(383f / 527f)
                        ) {
                            PostImageView(
                                viewModel.moment?.images ?: emptyList(),
                                initialPage = initImagePagerIndex
                            )
                        }
                        PostDetails(
                            viewModel.moment
                        )
                        Spacer(modifier = Modifier.height(16.dp))
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                text = stringResource(
                                    R.string.comment_count,
                                    (viewModel.moment?.commentCount ?: 0)
                                ), fontSize = 14.sp,
                                fontWeight = FontWeight.Bold,
                                color = AppColors.nonActiveText
                            )
                            Spacer(modifier = Modifier.weight(1f))
                            OrderSelectionComponent() {
                                commentsViewModel.order = it
                                viewModel.reloadComment()
                            }
                        }

                        Spacer(modifier = Modifier.height(16.dp))
                    }
                    item {
                        CommentContent(
                            viewModel = commentsViewModel,
                            onLongClick = { comment ->
                                showCommentMenu = true
                                contextComment = comment
                            },
                            onReply = { parentComment, _, _, _ ->
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                    debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                                } else {
                                    replyComment = parentComment
                                    showCommentModal = true
                                }
                            }
                        )
                    }
                    item {
                        Spacer(modifier = Modifier.height(120.dp))
                    }

                }
            }

        }
    }

}

@Composable
fun CommentContent(
    viewModel: CommentsViewModel,
    onLongClick: (CommentEntity) -> Unit,
    onReply: (CommentEntity, Long?, String?, String?) -> Unit
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()

    val commentsList = viewModel.commentsList
    val addedTopLevelComment = viewModel.addedCommentList.filter {
        it.parentCommentId == null
    }
    Column(
        modifier = Modifier
            .padding(horizontal = 16.dp)
            .animateContentSize(animationSpec = tween(durationMillis = 500))
    ) {
        viewModel.highlightComment?.let {
            CommentItem(
                it,
                onLike = { comment ->
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                        debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                    } else {
                        // 使用防抖机制避免重复点击
                        viewModel.viewModelScope.launch {
                            if (comment.liked) {
                                viewModel.unlikeComment(comment.id)
                            } else {
                                viewModel.likeComment(comment.id)
                            }
                        }
                    }
                },
                onLongClick = { comment ->
                    onLongClick(comment)
                },
                onReply = { parentComment, _, _, _ ->
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                        debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                    } else {
                        onReply(
                            parentComment,
                            parentComment.author,
                            parentComment.name,
                            parentComment.avatar
                        )
                    }
                },
                onLoadMoreSubComments = {
                    viewModel.viewModelScope.launch {
                        viewModel.loadMoreSubComments(it.id)
                    }
                },

                )
        }

    }
    Column(
        modifier = Modifier
            .padding(horizontal = 16.dp)
            .animateContentSize(animationSpec = tween(durationMillis = 500))
    ) {
        for (item in addedTopLevelComment) {
            AnimatedVisibility(
                visible = true,
                enter = fadeIn() + slideInVertically(),
                exit = fadeOut() + slideOutVertically()
            ) {
                Box {
                    CommentItem(
                        item,
                        onLike = { comment ->
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                            } else {
                                // 防抖机制已在ViewModel中实现
                                viewModel.viewModelScope.launch {
                                    if (comment.liked) {
                                        viewModel.unlikeComment(comment.id)
                                    } else {
                                        viewModel.likeComment(comment.id)
                                    }
                                }
                            }
                        },
                        onLongClick = { comment ->
                            onLongClick(comment)
                        },
                        onReply = { parentComment, _, _, _ ->
                            onReply(
                                parentComment,
                                parentComment.author,
                                parentComment.name,
                                parentComment.avatar
                            )
                        },
                        onLoadMoreSubComments = {
                            viewModel.viewModelScope.launch {
                                viewModel.loadMoreSubComments(it.id)
                            }
                        },
                        addedCommentList = viewModel.addedCommentList
                    )
                }
            }
        }
    }

    commentsList.forEach { item ->
        if (
            item.id != viewModel.highlightCommentId &&
            viewModel.addedCommentList.none { it.id == item.id }
        ) {
            AnimatedVisibility(
                visible = true,
                enter = slideInVertically(),
                exit = slideOutVertically()
            ) {
                Box(
                    modifier = Modifier.padding(horizontal = 16.dp)
                ) {
                    CommentItem(
                        item,
                        onLike = { comment ->
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                            } else {
                                // 防抖机制已在ViewModel中实现
                                viewModel.viewModelScope.launch {
                                    if (comment.liked) {
                                        viewModel.unlikeComment(comment.id)
                                    } else {
                                        viewModel.likeComment(comment.id)
                                    }
                                }
                            }
                        },
                        onLongClick = { comment ->
                            onLongClick(comment)
                        },
                        onReply = { parentComment, _, _, _ ->
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                debouncedNavigation {
                            debouncedNavigation {
                                                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                            }
                        }
                            } else {
                                onReply(
                                    parentComment,
                                    parentComment.author,
                                    parentComment.name,
                                    parentComment.avatar
                                )
                            }
                        },
                        onLoadMoreSubComments = {
                            viewModel.viewModelScope.launch {
                                viewModel.loadMoreSubComments(it.id)
                            }
                        },
                        addedCommentList = viewModel.addedCommentList
                    )
                }
            }
        }
    }

    // 加载状态处理
    if (viewModel.isLoading) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .height(120.dp),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                LinearProgressIndicator(
                    modifier = Modifier.width(160.dp),
                    color = AppColors.main
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Loading...",
                    fontSize = 14.sp
                )
            }
        }
        return
    }
    
    // 错误状态处理
    if (viewModel.hasError) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .height(120.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "Failed to load comments, click to retry",
                fontSize = 14.sp,
                modifier = Modifier.noRippleClickable {
                    viewModel.reloadComment()
                }
            )
        }
        return
    }
    
    // 评论为空
    if (commentsList.isEmpty() && addedTopLevelComment.isEmpty()) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = 1.dp),
            contentAlignment = Alignment.TopCenter
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally,
                modifier = Modifier.fillMaxWidth()
            ) {
                Image(
                    painter = painterResource(id = R.mipmap.invalid_name_3),
                    contentDescription = null,
                    modifier = Modifier.size(181.dp)
                )
                Spacer(modifier = Modifier.size(24.dp))
                androidx.compose.material.Text(
                    text = "没有人说话…",
                    color = AppColors.text,
                    fontSize = 16.sp,
                    fontWeight = FontWeight.W600
                )
                Spacer(modifier = Modifier.size(8.dp))
                androidx.compose.material.Text(
                    text = "留下评论，等AI和朋友回应你吧",
                    color = AppColors.secondaryText,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.W400
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Header(
    avatar: String?,
    nickname: String?,
    userId: Int?,
    isFollowing: Boolean,
    onFollowClick: () -> Unit,
    onDeleteClick: () -> Unit = {},
    onReportClick: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val context = LocalContext.current
    val debouncedNavigation = rememberDebouncedNavigation()
    var expanded by remember { mutableStateOf(false) }
    if (expanded) {
        ModalBottomSheet(
            onDismissRequest = {
                expanded = false
            },
            containerColor = AppColors.background,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        ) {
            PostMenuModal(

                onDeleteClick = {
                    onDeleteClick()
                    expanded = false
                },
                onReportClick = {
                    onReportClick()
                    expanded = false
                },
                userId = userId
            )
        }
    }
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        Image(
            painter = painterResource(id = R.drawable.rider_pro_back_icon), // Replace with your image resource
            contentDescription = "Back",
            modifier = Modifier
                .debouncedClickable {
                    debouncedNavigation {
                        navController.navigateUp()
                    }
                }
                .size(24.dp),
            colorFilter = ColorFilter.tint(AppColors.text)
        )
        Spacer(modifier = Modifier.width(8.dp))
        Box(
            modifier = Modifier
                .size(32.dp)
                .clip(CircleShape)
                .background(AppColors.secondaryText.copy(alpha = 0.1f))
        ) {
            CustomAsyncImage(
                context,
                avatar,
                contentDescription = "Profile Picture",
                modifier = Modifier
                    .size(32.dp)
                    .clip(CircleShape)
                    .debouncedClickable(debounceTime = 1000L) {
                        userId?.let {
                            debouncedNavigation {
                                navController.navigate(
                                    NavigationRoute.AccountProfile.route.replace(
                                        "{id}",
                                        userId.toString()
                                    )
                                )
                            }
                        }
                    },
                contentScale = ContentScale.Crop
            )
        }

        Spacer(modifier = Modifier.width(8.dp))
        Text(
            text = nickname ?: "",
            fontWeight = FontWeight.Bold,
            modifier = Modifier
                .weight(1f)
                .debouncedClickable(debounceTime = 1000L) {
                    userId?.let {
                        debouncedNavigation {
                            navController.navigate(
                                NavigationRoute.AccountProfile.route.replace(
                                    "{id}",
                                    userId.toString()
                                )
                            )
                        }
                    }
                },
            color = AppColors.text,
            fontSize = 17.sp
        )
        if (AppState.UserId != userId && !isFollowing) {
            FollowButton(
                isFollowing = false,
                onFollowClick = onFollowClick,
                fontSize = 12.sp
            )
            Spacer(modifier = Modifier.width(8.dp))
        }

        Box {
            Image(
                modifier = Modifier
                    .height(24.dp)
                    .padding(end = 8.dp)
                    .noRippleClickable {
                        if(GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.REPORT_CONTENT)){
                            debouncedNavigation{
                                navController.navigate(NavigationRoute.Login.route)
                            }
                    }else {
                            expanded = true
                        }
                    },
                painter = painterResource(id = R.drawable.rider_pro_more_horizon),
                contentDescription = "",
                colorFilter = ColorFilter.tint(AppColors.text)
            )
        }

    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ImageViewerDialog(
    images: List<MomentImageEntity>,
    initialPage: Int,
    onDismiss: () -> Unit
) {
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var currentPage by remember { mutableStateOf(initialPage) }
    val navigationBarPaddings =
        WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding() + 16.dp
    val showRawImageStates = remember { mutableStateListOf(*Array(images.size) { false }) }
    var isDownloading by remember { mutableStateOf(false) }
    
    BasicAlertDialog(
        onDismissRequest = {
            onDismiss()
        },
        modifier = Modifier.fillMaxWidth(),
        properties = DialogProperties(
            dismissOnBackPress = true,
            dismissOnClickOutside = true,
            usePlatformDefaultWidth = false,
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Black),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(0.8f)
            ) {
                val zoomState = rememberZoomState()
                CustomAsyncImage(
                    context,
                    if (showRawImageStates[currentPage]) images[currentPage].url else images[currentPage].thumbnail,
                    contentDescription = null,
                    modifier = Modifier
                        .fillMaxSize()
                        .zoomable(
                            zoomState = zoomState,
                            onTap = {
                                onDismiss()
                            }
                        ),
                    contentScale = ContentScale.Fit,
                )
                
                // Navigation arrows
                if (images.size > 1) {
                    Row(
                        modifier = Modifier.fillMaxSize(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // Left arrow
                        Box(
                            modifier = Modifier
                                .size(48.dp)
                                .noRippleClickable {
                                    if (currentPage > 0) {
                                        currentPage--
                                    }
                                },
                            contentAlignment = Alignment.Center
                        ) {
                            if (currentPage > 0) {
                                Text("<", color = Color.White, fontSize = 24.sp)
                            }
                        }
                        
                        // Right arrow
                        Box(
                            modifier = Modifier
                                .size(48.dp)
                                .noRippleClickable {
                                    if (currentPage < images.size - 1) {
                                        currentPage++
                                    }
                                },
                            contentAlignment = Alignment.Center
                        ) {
                            if (currentPage < images.size - 1) {
                                Text(">", color = Color.White, fontSize = 24.sp)
                            }
                        }
                    }
                }
            }
            
            Box(modifier = Modifier.padding(top = 10.dp, bottom = 10.dp)) {
                if (images.size > 1) {
                    Box(
                        modifier = Modifier
                            .clip(RoundedCornerShape(16.dp))
                            .background(Color(0xff333333).copy(alpha = 0.6f))
                            .padding(vertical = 4.dp, horizontal = 24.dp)
                    ) {
                        androidx.compose.material.Text(
                            text = "${currentPage + 1}/${images.size}",
                            color = Color.White,
                        )
                    }
                }
            }
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(0.2f)
                    .background(
                        Brush.verticalGradient(
                            colors = listOf(
                                Color.Transparent,
                                Color.Black
                            ),
                        )
                    )
                    .padding(start = 16.dp, end = 16.dp, bottom = navigationBarPaddings),
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 72.dp, end = 72.dp)
                        .padding(top = 16.dp),
                    horizontalArrangement = Arrangement.Center
                ) {
                    Column(
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier
                            .noRippleClickable {
                                if (isDownloading) {
                                    return@noRippleClickable
                                }
                                isDownloading = true
                                scope.launch {
                                    saveImageToGallery(context, images[currentPage].url)
                                    isDownloading = false
                                }
                            }
                    ) {
                        if (isDownloading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(32.dp),
                                color = Color.White
                            )
                        } else {
                            androidx.compose.material.Icon(
                                painter = painterResource(id = R.drawable.rider_pro_download_icon),
                                contentDescription = "",
                                modifier = Modifier.size(32.dp),
                                tint = Color.White
                            )
                        }

                        Spacer(modifier = Modifier.height(4.dp))
                        androidx.compose.material.Text(
                            stringResource(R.string.download),
                            color = Color.White
                        )
                    }
                    if (!showRawImageStates[currentPage]) {
                        Spacer(modifier = Modifier.weight(1f))
                    }
                    if (!showRawImageStates[currentPage]) {
                        Column(
                            verticalArrangement = Arrangement.Center,
                            horizontalAlignment = Alignment.CenterHorizontally,
                            modifier = Modifier.noRippleClickable {
                                showRawImageStates[currentPage] = true
                            }
                        ) {
                            androidx.compose.material.Icon(
                                painter = painterResource(id = R.drawable.rider_pro_original_raw),
                                contentDescription = "",
                                modifier = Modifier.size(32.dp),
                                tint = Color.White
                            )
                            Spacer(modifier = Modifier.height(4.dp))
                            androidx.compose.material.Text(
                                stringResource(R.string.original),
                                color = Color.White
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
fun PostImageView(
    images: List<MomentImageEntity>,
    initialPage: Int? = 0
) {
    val context = LocalContext.current
    var isImageViewerDialog by remember { mutableStateOf(false) }
    var currentImageIndex by remember { mutableStateOf(initialPage ?: 0) }
    
    DisposableEffect(Unit) {
        onDispose {
            isImageViewerDialog = false
        }
    }
    
    if (isImageViewerDialog) {
        ImageViewerDialog(
            images = images,
            initialPage = currentImageIndex
        ) {
            isImageViewerDialog = false
        }
    }
    
    Column(
        modifier = Modifier
    ) {
        if (images.isNotEmpty()) {
            CustomAsyncImage(
                context,
                images[currentImageIndex].thumbnail,
                contentDescription = "Image",
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .pointerInput(Unit) {
                        detectTapGestures(
                            onTap = {
                                isImageViewerDialog = true
                            }
                        )
                    }
                    .background(Color.Gray.copy(alpha = 0.1f))
            )
        }

        // 图片导航控件
        if (images.size > 1) {
            Row(
                modifier = Modifier
                    .padding(8.dp)
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Previous button
                Text(
                    text = "Previous",
                    modifier = Modifier
                        .padding(8.dp)
                        .noRippleClickable {
                            if (currentImageIndex > 0) {
                                currentImageIndex--
                            }
                        },
                    color = if (currentImageIndex > 0) Color.Blue else Color.Gray
                )
                
                // Indicators
                Row(
                    horizontalArrangement = Arrangement.Center
                ) {
                    images.forEachIndexed { index, _ ->
                        Box(
                            modifier = Modifier
                                .size(4.dp)
                                .clip(CircleShape)
                                .background(
                                    if (currentImageIndex == index) Color.Red else Color.Gray.copy(
                                        alpha = 0.5f
                                    )
                                )
                                .padding(4.dp)
                        )
                        if (index < images.size - 1) {
                            Spacer(modifier = Modifier.width(8.dp))
                        }
                    }
                }
                
                // Next button
                Text(
                    text = "Next",
                    modifier = Modifier
                        .padding(8.dp)
                        .noRippleClickable {
                            if (currentImageIndex < images.size - 1) {
                                currentImageIndex++
                            }
                        },
                    color = if (currentImageIndex < images.size - 1) Color.Blue else Color.Gray
                )
            }
        }
    }
}


@Composable
fun PostDetails(
    momentEntity: MomentEntity?
) {
    val AppColors = LocalAppTheme.current
    Column(
        modifier = Modifier
            .padding(start = 16.dp, end = 16.dp, top = 12.dp)
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        if (!momentEntity?.momentTextContent.isNullOrEmpty()) {
            Text(
                text = com.aiosman.ravenow.utils.Utils.unescapeHtml(momentEntity?.momentTextContent),
                fontSize = 14.sp,
                color = AppColors.text,
            )
        }
        Text(
            modifier = Modifier.padding(top = 16.dp),
            text = "${momentEntity?.time?.formatPostTime()}",
            color = AppColors.nonActiveText,
            fontSize = 12.sp)
    }
}

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun CommentItem(
    commentEntity: CommentEntity,
    isChild: Boolean = false,
    onLike: (commentEntity: CommentEntity) -> Unit = {},
    onReply: (
        parentComment: CommentEntity,
        replyUserId: Long?,
        replyUserNickname: String?,
        replyUserAvatar: String?
    ) -> Unit = { _, _, _, _ -> },
    onLoadMoreSubComments: ((CommentEntity) -> Unit)? = {},
    onLongClick: (CommentEntity) -> Unit = {},
    addedCommentList: List<CommentEntity> = emptyList()
) {
    val AppColors = LocalAppTheme.current
    val context = LocalContext.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        Row(modifier = Modifier.padding(vertical = 8.dp)) {
            Box(
                modifier = Modifier
                    .size(if (isChild) 24.dp else 32.dp)
                    .clip(CircleShape)
                    .background(Color.Gray.copy(alpha = 0.1f))
            ) {
                CustomAsyncImage(
                    context = context,
                    imageUrl = commentEntity.avatar,
                    contentDescription = "Comment Profile Picture ${commentEntity.name}",
                    modifier = Modifier
                        .size(if (isChild) 24.dp else 32.dp)
                        .clip(CircleShape)
                        .debouncedClickable(debounceTime = 1000L) {
                            debouncedNavigation {
                                navController.navigate(
                                    NavigationRoute.AccountProfile.route.replace(
                                        "{id}",
                                        commentEntity.author.toString()
                                    )
                                )
                            }
                        },
                    contentScale = ContentScale.Crop
                )
            }
            Spacer(modifier = Modifier.width(8.dp))
            Column(
                modifier = Modifier
                    .weight(1f)
                    .combinedClickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = null,
                        onLongClick = {
                            onLongClick(commentEntity)
                        }
                    ) {}
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = commentEntity.name,
                        fontWeight = FontWeight.Bold,
                        fontSize = 11.sp,
                        color = AppColors.text
                    )
                    Column(
                        horizontalAlignment = Alignment.End
                    ) {
                        AnimatedLikeIcon(
                            liked = commentEntity.liked,
                            onClick = {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                                } else {
                                    onLike(commentEntity)
                                }
                            },
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            text = commentEntity.likes.toString(),
                            fontSize = 12.sp,
                            fontWeight = FontWeight.Bold,
                            color = AppColors.text,
                            modifier = Modifier.padding(top = 4.dp,end = 4.dp)
                        )
                    }
                }


                    Text(
                        text = com.aiosman.ravenow.utils.Utils.unescapeHtml(commentEntity.comment),
                        fontSize = 13.sp,
                        maxLines = Int.MAX_VALUE,
                        softWrap = true,
                        lineHeight = 20.sp,
                        color = AppColors.text,
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(end = 50.dp)
                            .padding(top = 0.dp)
                            .combinedClickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = null,
                                onLongClick = {
                                    onLongClick(
                                        commentEntity
                                    )
                                },
                            ) {

                            }
                    )


                Row (
                    modifier = Modifier.padding(top = 12.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ){
                    Text(
                        text = commentEntity.date.timeAgo(context),
                        fontSize = 12.sp,
                        color = Color.Gray
                    )

                    Spacer(modifier = Modifier.width(8.dp))

                    Text(
                        text = stringResource(R.string.reply),
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = AppColors.nonActiveText,
                        modifier = Modifier.noRippleClickable {
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                debouncedNavigation {
                                    navController.navigate(NavigationRoute.Login.route)
                                }
                            } else {
                                onReply(
                                    commentEntity,
                                    commentEntity.replyUserId,
                                    commentEntity.replyUserNickname,
                                    commentEntity.replyUserAvatar
                                )
                            }
                        },
                    )
                }
            }
        }
        Spacer(modifier = Modifier.height(8.dp))
        Column(
            modifier = Modifier
                .padding(start = 12.dp + 40.dp)
                .animateContentSize(
                    animationSpec = tween(
                        durationMillis = 500
                    )
                )
        ) {
            val addedCommentList =
                addedCommentList.filter { it.parentCommentId == commentEntity.id }
            addedCommentList.forEach { addedComment ->
                CommentItem(
                    addedComment,
                    isChild = true,
                    onLike = onLike,
                    onReply = onReply,
                    onLongClick = onLongClick
                )
            }
            commentEntity.reply.forEach { reply ->
                CommentItem(
                    reply,
                    isChild = true,
                    onLike = onLike,
                    onReply = onReply,
                    onLongClick = { comment ->
                        onLongClick(comment)
                    }
                )
            }
            if (commentEntity.replyCount > 0 && !isChild && commentEntity.reply.size < commentEntity.replyCount) {
                val remaining = commentEntity.replyCount - commentEntity.reply.size
                Text(
                    text = stringResource(R.string.view_more_reply, remaining),
                    fontSize = 14.sp,
                    color = AppColors.nonActiveText,
                    modifier = Modifier.noRippleClickable {
                        onLoadMoreSubComments?.invoke(commentEntity)
                    }
                )
            }

        }
    }
}


@Composable
fun PostBottomBar(
    onCreateCommentClick: () -> Unit = {},
    onLikeClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {},
    momentEntity: MomentEntity?
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()

    Column(
        modifier = Modifier.background(
            AppColors.background
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .background(AppColors.inputBackground)
        ) {

        }
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 13.dp)
                .background(AppColors.background)
        ) {
            // grey round box
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .background(AppColors.inputBackground)
                    .weight(1f)
                    .height(31.dp)
                    .padding(8.dp)
                    .noRippleClickable {
                        // 检查游客模式，如果是游客则跳转登录
                        if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                            debouncedNavigation {
                                navController.navigate(NavigationRoute.Login.route)
                            }
                        } else {
                            onCreateCommentClick()
                        }
                    }
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        ImageVector.vectorResource(R.drawable.rider_pro_new_comment),
                        contentDescription = "Send",
                        colorFilter = ColorFilter.tint(AppColors.text),
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = stringResource(R.string.post_comment_hint),
                        fontSize = 12.sp,
                        color = AppColors.text
                    )
                }
            }
            Spacer(modifier = Modifier.width(16.dp))
            AnimatedFavouriteIcon(
                isFavourite = momentEntity?.isFavorite == true,
                onClick = {
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                        debouncedNavigation {
                            navController.navigate(NavigationRoute.Login.route)
                        }
                    } else {
                        onFavoriteClick()
                    }
                },
                modifier = Modifier.size(24.dp)
            )

            Spacer(modifier = Modifier.width(4.dp))
            Text(text = momentEntity?.favoriteCount.toString(), color = AppColors.text)
            Spacer(modifier = Modifier.width(16.dp))
            AnimatedLikeIcon(
                liked = momentEntity?.liked == true,
                onClick = {
                    // 检查游客模式，如果是游客则跳转登录
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                        debouncedNavigation {
                            navController.navigate(NavigationRoute.Login.route)
                        }
                    } else {
                        onLikeClick()
                    }
                },
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.width(4.dp))
            Text(text = momentEntity?.likeCount.toString(), color = AppColors.text)
        }
        BottomNavigationPlaceholder(
            color = AppColors.background
        )
    }

}


@Composable
fun PostMenuModal(
    onDeleteClick: () -> Unit = {},
    onReportClick: () -> Unit = {},
    userId: Int? = 0
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .height(160.dp)
            .background(AppColors.background)
            .padding(vertical = 47.dp, horizontal = 20.dp)
    ) {
        if(AppState.UserId == userId){
            Row(
                modifier = Modifier
                    .size(60.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(
                    modifier = Modifier.padding(end = 16.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Box(
                        modifier = Modifier
                            .clip(CircleShape)
                            .noRippleClickable {
                                onDeleteClick()
                            }
                    ) {
                        Image(
                            painter = painterResource(id = R.drawable.rider_pro_moment_delete),
                            contentDescription = "",
                            modifier = Modifier.size(24.dp),
                            colorFilter = ColorFilter.tint(
                                AppColors.text
                            )
                        )
                    }

                    Spacer(modifier = Modifier.height(8.dp))
                    Text(
                        text = stringResource(R.string.delete),
                        fontSize = 12.sp,
                        fontWeight = FontWeight.Bold,
                        color = AppColors.text
                    )
                }
            }
        }

        Row(
            modifier = Modifier
                .size(60.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.padding(end = 16.dp),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Box(
                    modifier = Modifier
                        .clip(CircleShape)
                        .noRippleClickable {
                            // 检查游客模式，如果是游客则跳转登录
                            if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.REPORT_CONTENT)) {
                                debouncedNavigation {
                                    navController.navigate(NavigationRoute.Login.route)
                                }
                            } else {
                                onReportClick()
                            }
                        }
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.rider_pro_moment_report),
                        contentDescription = "",
                        modifier = Modifier.size(24.dp),
                        colorFilter = ColorFilter.tint(
                            AppColors.error
                        )
                    )
                }

                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = stringResource(R.string.report),
                    fontSize = 12.sp,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.error
                )
            }
        }

    }
}


@Composable
fun MenuActionItem(
    icon: Int? = null,
    text: String,
    content: @Composable() (() -> Unit)? = null,
    onClick: () -> Unit
) {
    val AppColors = LocalAppTheme.current

    Column(
        modifier = Modifier,
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = Modifier
                .clip(CircleShape)
                .noRippleClickable {
                    onClick()
                }
        ) {
            content?.invoke()
            if (icon != null) {
                Icon(
                    painter = painterResource(id = icon),
                    contentDescription = "",
                    modifier = Modifier.size(24.dp),
                    tint = AppColors.text
                )
            }
        }

        Spacer(modifier = Modifier.height(8.dp))
        Text(
            text = text,
            fontSize = 11.sp,
            fontWeight = FontWeight.Bold,
            color = AppColors.text
        )
    }
}

/**
 * 评论菜单弹窗
 */
@Composable
fun CommentMenuModal(
    onDeleteClick: () -> Unit = {},
    commentEntity: CommentEntity? = null,
    onCloseClick: () -> Unit = {},
    onLikeClick: () -> Unit = {},
    onReplyClick: () -> Unit = {},
    isSelf: Boolean = false
) {
    val clipboard = LocalClipboardManager.current
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()

    fun copyToClipboard() {
        commentEntity?.let {
            clipboard.setText(
                AnnotatedString(
                    text = it.comment,
                )
            )
        }
    }
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(AppColors.background)
            .padding(vertical = 24.dp, horizontal = 20.dp)
    ) {
        Text(
            stringResource(R.string.comment),
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
            color = AppColors.text
        )
        Spacer(modifier = Modifier.height(24.dp))
        commentEntity?.let {
            Column(
                modifier = Modifier
                    .clip(RoundedCornerShape(8.dp))
                    .background(
                        AppColors.nonActive
                    )

                    .padding(8.dp)
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,

                    ) {
                    Box(
                        modifier = Modifier
                            .size(24.dp)
                            .clip(CircleShape)
                    ) {
                        CustomAsyncImage(
                            imageUrl = it.avatar,
                            modifier = Modifier.fillMaxSize(),
                            contentDescription = "Avatar",
                        )
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    androidx.compose.material.Text(
                        it.name,
                        fontWeight = FontWeight.Bold,
                        fontSize = 16.sp,
                        color = AppColors.text
                    )
                }
                Spacer(modifier = Modifier.height(4.dp))
                androidx.compose.material.Text(
                    it.comment,
                    maxLines = 1,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 32.dp),
                    overflow = TextOverflow.Ellipsis,
                    color = AppColors.text
                )
            }
            Spacer(modifier = Modifier.height(32.dp))
        }

        Row(
            modifier = Modifier
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            if (isSelf) {
                MenuActionItem(
                    icon = R.drawable.rider_pro_moment_delete,
                    text = stringResource(R.string.delete)
                ) {
                    onDeleteClick()
                }

                Spacer(modifier = Modifier.width(48.dp))
            }
            MenuActionItem(
                icon = R.drawable.rider_pro_copy,
                text = stringResource(R.string.copy)
            ) {
                copyToClipboard()
                onCloseClick()
            }
            commentEntity?.let {
                Spacer(modifier = Modifier.width(48.dp))
                MenuActionItem(
                    text = stringResource(R.string.like),
                    content = {
                        AnimatedLikeIcon(
                            liked = it.liked,
                            onClick = {
                                // 检查游客模式，如果是游客则跳转登录
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                                } else {
                                    onLikeClick()
                                }
                            },
                            modifier = Modifier.size(24.dp)
                        )
                    }
                ) {
                    onCloseClick()
                }
            }
            //自己也可以回复自己
            Spacer(modifier = Modifier.width(48.dp))
            MenuActionItem(
                icon = R.drawable.rider_pro_comment,
                text = stringResource(R.string.reply)
            ) {
                // 检查游客模式，如果是游客则跳转登录
                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                    debouncedNavigation {
                        navController.navigate(NavigationRoute.Login.route)
                    }
                } else {
                    onReplyClick()
                }
            }

        }
        Spacer(modifier = Modifier.height(48.dp))
    }
}



@Composable
fun OrderSelectionComponent(
    onSelected: (String) -> Unit = {}
) {
    val AppColors = LocalAppTheme.current

    var selectedOrder by remember { mutableStateOf("like") }
    val orders = listOf(
        "like" to stringResource(R.string.order_comment_default),
        "earliest" to stringResource(R.string.order_comment_earliest),
        "latest" to stringResource(R.string.order_comment_latest)
    )
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(8.dp))
            .background(AppColors.nonActive)

    ) {
        Row(
            horizontalArrangement = Arrangement.SpaceBetween,
            modifier = Modifier
                .padding(4.dp)
                .clip(RoundedCornerShape(6.dp))
        ) {
            orders.forEach { order ->
                Box(
                    modifier = Modifier
                        .noRippleClickable {
                            selectedOrder = order.first
                            onSelected(order.first)
                        }
                        .background(
                            if (
                                selectedOrder == order.first
                            ) AppColors.background else Color.Transparent
                        )
                        .padding(vertical = 2.dp, horizontal = 8.dp),
                ) {
                    Text(
                        text = order.second,
                        color = AppColors.text,
                        fontSize = 12.sp
                    )
                }

            }
        }
    }

}

@Composable
fun ReportModal(
    momentId: Int,
    onClose: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val commonService : CommonService = CommonServiceImpl()
    val scope = rememberCoroutineScope()
    val context = LocalContext.current
    var reasonMapping by remember { mutableStateOf(mutableMapOf<Int,String>()) }
    var result:Boolean? by remember { mutableStateOf(null) }
    fun loadReportOptions() {
        scope.launch {
            val reportOptions = commonService.getReportReasons()
            val newReasonMapping :MutableMap<Int,String> = mutableMapOf()
            reportOptions.reasons.forEach { option ->
                option.getReasonText(context)?.let {
                    newReasonMapping[option.id] = it
                }
            }
            reasonMapping = newReasonMapping
        }
    }
    fun createReport(code:Int) {
        scope.launch {
            try {
                commonService.createReport(
                    reportReasonId = code,
                    reportType = "post",
                    reportId = momentId
                )
                result = true
            }catch (e:Exception) {
                e.printStackTrace()
                result = false
            }

        }
    }
    LaunchedEffect(Unit) {
        loadReportOptions()
    }
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .background(AppColors.background)
            .padding(start = 24.dp, end = 24.dp, bottom = 64.dp)
    ) {
        Box(
            modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 16.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                stringResource(R.string.report),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = AppColors.text
            )
        }

        // divider
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .background(AppColors.divider)
        ) {

        }

        if (result == null) {

            Column(
                modifier = Modifier.fillMaxWidth().padding(top = 24.dp, bottom = 24.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text(
                    stringResource(R.string.report_title),
                    fontSize = 20.sp,
                    color = AppColors.text,
                    textAlign = TextAlign.Center,
                    fontWeight = FontWeight.Bold,

                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    stringResource(R.string.report_description),
                    fontSize = 14.sp,
                    color = AppColors.secondaryText,
                    textAlign = TextAlign.Center
                )

            }

            // report options,scroll list
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .verticalScroll(rememberScrollState())
            ) {
                reasonMapping.forEach { (id, reason) ->
                    Column(
                        modifier = Modifier.noRippleClickable {
                            createReport(id)
                        }
                    ) {
                        // divider
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .height(1.dp)
                                .background(AppColors.divider)
                        ) {

                        }
                        Row(
                            modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(
                                modifier = Modifier.weight(1f),
                                text = reason,
                                fontSize = 14.sp,
                                color = AppColors.text
                            )
                            // right icon
                            Icon(
                                painter = painterResource(id = R.drawable.rider_pro_nav_next),
                                contentDescription = "",
                                modifier = Modifier.size(24.dp),
                                tint = AppColors.text
                            )

                        }
                    }

                }
            }
        }else{
            Column(
                modifier = Modifier.fillMaxWidth().weight(1f)

            ) {
                Box(
                    modifier = Modifier.fillMaxWidth().padding(top = 24.dp, bottom = 24.dp),
                    contentAlignment = Alignment.Center
                ) {
                    if (result == true) {
                        Text(
                            stringResource(R.string.report_success_desc),
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = AppColors.text
                        )
                    }
                    if (result == false) {
                        Text(
                            stringResource(R.string.report_fail_desc),
                            fontSize = 18.sp,
                            fontWeight = FontWeight.Bold,
                            color = AppColors.text
                        )
                    }
                }
                Spacer(
                    modifier = Modifier.weight(1f)
                )
                ActionButton(
                    text = stringResource(R.string.close),
                    click = {
                        onClose()
                    }
                )
            }
        }
    }
}