package com.aiosman.riderpro.ui.post

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalSharedTransitionApi
import androidx.compose.animation.animateContentSize
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.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.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.LinearProgressIndicator
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.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
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.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.aiosman.riderpro.AppState
import com.aiosman.riderpro.LocalAnimatedContentScope
import com.aiosman.riderpro.LocalNavController
import com.aiosman.riderpro.LocalSharedTransitionScope
import com.aiosman.riderpro.R
import com.aiosman.riderpro.entity.CommentEntity
import com.aiosman.riderpro.entity.MomentEntity
import com.aiosman.riderpro.entity.MomentImageEntity
import com.aiosman.riderpro.exp.formatPostTime
import com.aiosman.riderpro.exp.timeAgo
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.comment.NoticeScreenHeader
import com.aiosman.riderpro.ui.composables.AnimatedFavouriteIcon
import com.aiosman.riderpro.ui.composables.AnimatedLikeIcon
import com.aiosman.riderpro.ui.composables.BottomNavigationPlaceholder
import com.aiosman.riderpro.ui.composables.CustomAsyncImage
import com.aiosman.riderpro.ui.composables.CustomClickableText
import com.aiosman.riderpro.ui.composables.EditCommentBottomModal
import com.aiosman.riderpro.ui.composables.FollowButton
import com.aiosman.riderpro.ui.composables.StatusBarSpacer
import com.aiosman.riderpro.ui.imageviewer.ImageViewerViewModel
import com.aiosman.riderpro.ui.modifiers.noRippleClickable
import kotlinx.coroutines.launch

@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 {
                return PostViewModel(id) as T
            }
        }
    )
    val commentsViewModel = viewModel.commentsViewModel
    val scope = rememberCoroutineScope()
    val navController = LocalNavController.current
    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
    )
    LaunchedEffect(Unit) {
        viewModel.initData(
            highlightCommentId = highlightCommentId.let {
                if (it == 0) null else it
            }
        )
    }

    if (showCommentMenu) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentMenu = false
            },
            containerColor = Color.White,
            sheetState = commentModalState,
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            windowInsets = WindowInsets(0)
        ) {
            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 = {
                    scope.launch {
                        commentModalState.hide()
                        showCommentMenu = false
                    }
                    contextComment?.let {
                        viewModel.viewModelScope.launch {
                            if (it.liked) {
                                viewModel.unlikeComment(it.id)
                            } else {
                                viewModel.likeComment(it.id)
                            }
                        }
                    }

                },
                onReplyClick = {
                    scope.launch {
                        commentModalState.hide()
                        showCommentMenu = false
                        replyComment = contextComment
                        showCommentModal = true
                    }
                }
            )
        }
    }
    if (showCommentModal) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentModal = false
            },
            containerColor = Color.White,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            windowInsets = WindowInsets(0)
        ) {
            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
                }

            }
        }
    }
    Scaffold(
        modifier = Modifier.fillMaxSize(),
        bottomBar = {
            if (!viewModel.isError) {
                PostBottomBar(
                    onLikeClick = {
                        scope.launch {
                            if (viewModel.moment?.liked == true) {
                                viewModel.dislikeMoment()
                            } else {
                                viewModel.likeMoment()
                            }
                        }
                    },
                    onCreateCommentClick = {
                        replyComment = null
                        showCommentModal = true
                    },
                    onFavoriteClick = {
                        scope.launch {
                            if (viewModel.moment?.isFavorite == true) {
                                viewModel.unfavoriteMoment()
                            } else {
                                viewModel.favoriteMoment()
                            }
                        }
                    },
                    momentEntity = viewModel.moment
                )
            }

        }
    ) {
        it
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.White)
        ) {
            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
                        )
                    )
                }
            } else {
                Header(
                    avatar = viewModel.avatar,
                    nickname = viewModel.nickname,
                    userId = viewModel.moment?.authorId,
                    isFollowing = viewModel.moment?.followStatus == true,
                    onFollowClick = {
                        scope.launch {
                            if (viewModel.moment?.followStatus == true) {
                                viewModel.unfollowUser()
                            } else {
                                viewModel.followUser()
                            }
                        }
                    },
                    onDeleteClick = {
                        viewModel.deleteMoment {
                            navController.popBackStack()
                        }
                    }
                )
                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))
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(horizontal = 16.dp)
                                .height(1.dp)
                                .background(Color(0xFFF7F7F7))
                        ) {

                        }
                        Spacer(modifier = Modifier.height(24.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
                            )
                            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, _, _, _ ->
                                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 commentsPagging = viewModel.commentsFlow.collectAsLazyPagingItems()
    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 ->
                    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)
                    }
                },

                )
        }

    }
    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 ->
                            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
                    )
                }
            }
        }
    }

    for (idx in 0 until commentsPagging.itemCount) {
        val item = commentsPagging[idx] ?: return
        if (item.id != viewModel.highlightCommentId) {
            AnimatedVisibility(
                visible = true,
                enter = slideInVertically(),
                exit = slideOutVertically()
            ) {
                Box(
                    modifier = Modifier.padding(horizontal = 16.dp)
                ) {
                    CommentItem(
                        item,
                        onLike = { comment ->
                            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
                    )
                }
            }
        }

    }

    // Handle loading and error states as before
    if (commentsPagging.loadState.refresh is LoadState.Loading) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .height(120.dp),
            contentAlignment = Alignment.Center
        ) {
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                LinearProgressIndicator(
                    modifier = Modifier.width(160.dp),
                    color = Color(0xFFDA3832)
                )
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "Loading...",
                    fontSize = 14.sp
                )
            }
        }
        return
    }
    if (commentsPagging.loadState.append is LoadState.Loading) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .height(64.dp),
            contentAlignment = Alignment.Center
        ) {
            LinearProgressIndicator(
                modifier = Modifier.width(160.dp),
                color = Color(0xFFDA3832)
            )
        }
    }
    if (commentsPagging.loadState.refresh is LoadState.Error) {
        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()
                }
            )
        }
    }
    if (commentsPagging.loadState.append is LoadState.Error) {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .height(64.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = "Failed to load more comments, click to retry",
                fontSize = 14.sp,
                modifier = Modifier.noRippleClickable {
                    commentsPagging.retry()
                }
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Header(
    avatar: String?,
    nickname: String?,
    userId: Int?,
    isFollowing: Boolean,
    onFollowClick: () -> Unit,
    onDeleteClick: () -> Unit = {}
) {
    val navController = LocalNavController.current
    val context = LocalContext.current
    var expanded by remember { mutableStateOf(false) }
    if (expanded) {
        ModalBottomSheet(
            onDismissRequest = {
                expanded = false
            },
            containerColor = Color.White,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
            windowInsets = WindowInsets(0)
        ) {
            PostMenuModal(
                onDeleteClick = {
                    onDeleteClick()
                    expanded = false
                }
            )
        }
    }
    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
                .noRippleClickable {
                    navController.popBackStack()
                }
                .size(32.dp)
        )
        Spacer(modifier = Modifier.width(8.dp))
        Box(
            modifier = Modifier
                .size(40.dp)
                .clip(CircleShape)
                .background(Color.Gray.copy(alpha = 0.1f))
        ) {
            CustomAsyncImage(
                context,
                avatar,
                contentDescription = "Profile Picture",
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
                    .noRippleClickable {
                        userId?.let {
                            navController.navigate(
                                NavigationRoute.AccountProfile.route.replace(
                                    "{id}",
                                    userId.toString()
                                )
                            )
                        }
                    },
                contentScale = ContentScale.Crop
            )
        }

        Spacer(modifier = Modifier.width(8.dp))
        Text(text = nickname ?: "", fontWeight = FontWeight.Bold)
//        if (AppState.UserId != userId) {
//            FollowButton(
//                isFollowing = isFollowing,
//                onFollowClick = onFollowClick,
//                imageModifier = Modifier
//                    .height(18.dp)
//                    .width(80.dp),
//                fontSize = 12.sp
//            )
//        }
        if (AppState.UserId == userId) {
            Spacer(modifier = Modifier.weight(1f))
            Box {
                Image(
                    modifier = Modifier
                        .height(20.dp)
                        .padding(end = 8.dp)
                        .noRippleClickable {
                            expanded = true
                        },
                    painter = painterResource(id = R.drawable.rider_pro_more_horizon),
                    contentDescription = ""
                )
            }
        }
    }
}


@OptIn(ExperimentalFoundationApi::class, ExperimentalSharedTransitionApi::class)
@Composable
fun PostImageView(
    images: List<MomentImageEntity>,
    initialPage: Int? = 0
) {
    val pagerState = rememberPagerState(pageCount = { images.size }, initialPage = initialPage ?: 0)
    val navController = LocalNavController.current
    val sharedTransitionScope = LocalSharedTransitionScope.current
    val animatedVisibilityScope = LocalAnimatedContentScope.current
    val context = LocalContext.current

    Column {
        HorizontalPager(
            state = pagerState,
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .background(Color.Gray.copy(alpha = 0.1f)),
        ) { page ->
            val image = images[page]
            with(sharedTransitionScope) {
                CustomAsyncImage(
                    context,
                    image.thumbnail,
                    contentDescription = "Image",
                    contentScale = ContentScale.Crop,
                    modifier = Modifier
                        .sharedElement(
                            rememberSharedContentState(key = image),
                            animatedVisibilityScope = animatedVisibilityScope
                        )
                        .fillMaxSize()
                        .noRippleClickable {
                            ImageViewerViewModel.asNew(images, page)
                            navController.navigate(
                                NavigationRoute.ImageViewer.route
                            )
                        }
                )
            }
        }

        // Indicator container
        Row(
            modifier = Modifier
                .padding(8.dp)
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.Center
        ) {
            if (images.size > 1) {
                images.forEachIndexed { index, _ ->
                    Box(
                        modifier = Modifier
                            .size(4.dp)
                            .clip(CircleShape)
                            .background(
                                if (pagerState.currentPage == index) Color.Red else Color.Gray.copy(
                                    alpha = 0.5f
                                )
                            )
                            .padding(4.dp)


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

}

@Composable
fun PostDetails(
    momentEntity: MomentEntity?
) {

    Column(
        modifier = Modifier
            .padding(start = 16.dp, end = 16.dp, top = 12.dp)
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        if (!momentEntity?.momentTextContent.isNullOrEmpty()) {
            Text(
                text = momentEntity?.momentTextContent ?: "",
                fontSize = 16.sp,
                fontWeight = FontWeight.Bold,
            )
        }
        Text(text = "${momentEntity?.time?.formatPostTime()}")
    }
}

@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 context = LocalContext.current
    val navController = LocalNavController.current
    Column(
        modifier = Modifier
            .fillMaxWidth()
    ) {
        Row(modifier = Modifier.padding(vertical = 8.dp)) {
            Box(
                modifier = Modifier
                    .size(if (isChild) 24.dp else 40.dp)
                    .background(Color.Gray.copy(alpha = 0.1f))
                    .noRippleClickable {
                        navController.navigate(
                            NavigationRoute.AccountProfile.route.replace(
                                "{id}",
                                commentEntity.author.toString()
                            )
                        )
                    }
            ) {
                CustomAsyncImage(
                    context = context,
                    imageUrl = commentEntity.avatar,
                    contentDescription = "Comment Profile Picture",
                    modifier = Modifier.size(if (isChild) 24.dp else 40.dp),
                    contentScale = ContentScale.Crop
                )
            }
            Spacer(modifier = Modifier.width(8.dp))
            Column(
                modifier = Modifier
                    .weight(1f)
                    .combinedClickable(
                        interactionSource = remember { MutableInteractionSource() },
                        indication = null,
                        onLongClick = {
                            onLongClick(commentEntity)
                        }
                    ) {}
            ) {
                Text(text = commentEntity.name, fontWeight = FontWeight.W600, fontSize = 14.sp)
                Row {
                    if (isChild) {
                        val annotatedText = buildAnnotatedString {
                            if (commentEntity.replyUserId != null) {
                                pushStringAnnotation(
                                    tag = "replyUser",
                                    annotation = commentEntity.replyUserId.toString()
                                )
                                withStyle(
                                    style = SpanStyle(
                                        fontWeight = FontWeight.W600,
                                        color = Color(0xFF6F94AE)
                                    )
                                ) {
                                    append("@${commentEntity.replyUserNickname}")
                                }
                                pop()
                            }
                            append(" ${commentEntity.comment}")

                        }
                        Box {
                            CustomClickableText(
                                text = annotatedText,
                                onClick = { offset ->
                                    annotatedText.getStringAnnotations(
                                        tag = "replyUser",
                                        start = offset,
                                        end = offset
                                    ).firstOrNull()?.let {
                                        navController.navigate(
                                            NavigationRoute.AccountProfile.route.replace(
                                                "{id}",
                                                it.item
                                            )
                                        )
                                    }
                                },
                                style = TextStyle(fontSize = 14.sp),
                                onLongPress = {
                                    onLongClick(commentEntity)
                                },
                            )
                        }

                    } else {
                        Text(
                            text = commentEntity.comment,
                            fontSize = 14.sp,
                            maxLines = Int.MAX_VALUE,
                            softWrap = true,
                            modifier = Modifier.combinedClickable(
                                interactionSource = remember { MutableInteractionSource() },
                                indication = null,
                                onLongClick = {
                                    onLongClick(
                                        commentEntity
                                    )
                                },
                            ) {

                            }
                        )
                    }
                }
                Row {
                    Text(
                        text = commentEntity.date.timeAgo(context),
                        fontSize = 12.sp,
                        color = Color.Gray
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    if (AppState.UserId?.toLong() != commentEntity.author) {
                        Text(
                            text = stringResource(R.string.reply),
                            fontSize = 12.sp,
                            color = Color.Gray,
                            modifier = Modifier.noRippleClickable {
                                onReply(
                                    commentEntity,
                                    commentEntity.replyUserId,
                                    commentEntity.replyUserNickname,
                                    commentEntity.replyUserAvatar
                                )
                            }
                        )
                    }

                }

            }
            Spacer(modifier = Modifier.width(16.dp))
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                AnimatedLikeIcon(
                    liked = commentEntity.liked,
                    onClick = {
                        onLike(commentEntity)
                    },
                    modifier = Modifier.size(20.dp)
                )
                Text(text = commentEntity.likes.toString(), fontSize = 12.sp)
            }
        }
        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 = 12.sp,
                    color = Color(0xFF6F94AE),
                    modifier = Modifier.noRippleClickable {
                        onLoadMoreSubComments?.invoke(commentEntity)
                    }
                )
            }

        }
    }
}

@Composable
fun PostBottomBar(
    onCreateCommentClick: () -> Unit = {},
    onLikeClick: () -> Unit = {},
    onFavoriteClick: () -> Unit = {},
    momentEntity: MomentEntity?
) {

    Column(
        modifier = Modifier.background(Color.White)
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(1.dp)
                .background(Color(0xFFF7F7F7))
        ) {

        }
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier
                .padding(horizontal = 16.dp, vertical = 13.dp)
                .background(Color.White)
        ) {
            // grey round box
            Box(
                modifier = Modifier
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color(0xFFF5F5F5))
                    .weight(1f)
                    .height(31.dp)
                    .padding(8.dp)
                    .noRippleClickable {
                        onCreateCommentClick()
                    }
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Image(
                        ImageVector.vectorResource(R.drawable.rider_pro_new_comment),
                        contentDescription = "Send"
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = stringResource(R.string.post_comment_hint),
                        fontSize = 12.sp,
                        color = Color(0xFFCCCCCC)
                    )
                }
            }
            Spacer(modifier = Modifier.width(16.dp))
            AnimatedLikeIcon(
                liked = momentEntity?.liked == true,
                onClick = onLikeClick,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.width(4.dp))
            Text(text = momentEntity?.likeCount.toString())
            Spacer(modifier = Modifier.width(16.dp))
            AnimatedFavouriteIcon(
                isFavourite = momentEntity?.isFavorite == true,
                onClick = onFavoriteClick,
                modifier = Modifier.size(24.dp)
            )
            Spacer(modifier = Modifier.width(4.dp))
            Text(text = momentEntity?.favoriteCount.toString())

        }
        BottomNavigationPlaceholder(
            color = Color.White
        )
    }

}

@Composable
fun PostMenuModal(
    onDeleteClick: () -> Unit = {}
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .height(160.dp)
            .padding(vertical = 47.dp, horizontal = 20.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier,
                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)
                    )
                }

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

@Composable
fun MenuActionItem(
    icon: Int? = null,
    text: String,
    content: @Composable() (() -> Unit)? = null,
    onClick: () -> Unit
) {
    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 = Color.Black
                )
            }
        }

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

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

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

                    .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
                    )
                }
                Spacer(modifier = Modifier.height(4.dp))
                androidx.compose.material.Text(
                    it.comment,
                    maxLines = 1,
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(start = 32.dp),
                    overflow = TextOverflow.Ellipsis
                )
            }
            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 = onLikeClick,
                            modifier = Modifier.size(24.dp)
                        )
                    }
                ) {
                    onCloseClick()
                }
            }
            if (!isSelf) {
                Spacer(modifier = Modifier.width(48.dp))
                MenuActionItem(
                    icon = R.drawable.rider_pro_comment,
                    text = stringResource(R.string.reply)
                ) {
                    onReplyClick()
                }
            }
        }
        Spacer(modifier = Modifier.height(48.dp))
    }
}

@Composable
fun OrderSelectionComponent(
    onSelected: (String) -> Unit = {}
) {
    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(Color(0xFFEEEEEE))

    ) {
        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
                            ) Color.White else Color.Transparent
                        )
                        .padding(vertical = 2.dp, horizontal = 8.dp),
                ) {
                    Text(
                        text = order.second,
                        color = Color.Black,
                        fontSize = 12.sp
                    )
                }

            }
        }
    }

}