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

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.asPaddingValues
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.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Text
import androidx.compose.material3.rememberModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
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 com.aiosman.ravenow.AppState
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.CommentService
import com.aiosman.ravenow.data.CommentServiceImpl
import com.aiosman.ravenow.entity.CommentEntity
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.composables.EditCommentBottomModal
import com.aiosman.ravenow.ui.composables.debouncedClickable
import com.aiosman.ravenow.ui.composables.rememberDebouncedNavigation
import com.aiosman.ravenow.ui.modifiers.noRippleClickable
import com.aiosman.ravenow.ui.post.CommentContent
import com.aiosman.ravenow.ui.post.CommentMenuModal
import com.aiosman.ravenow.ui.post.CommentsViewModel
import com.aiosman.ravenow.ui.post.OrderSelectionComponent
import kotlinx.coroutines.launch


class NewsCommentModalViewModel(
    val postId: Int?
) : ViewModel() {
    var commentsViewModel: CommentsViewModel = CommentsViewModel(postId.toString())
    var commentService: CommentService = CommentServiceImpl()
    
    init {
        commentsViewModel.preTransit()
    }

    fun likeComment(commentId: Int) {
        viewModelScope.launch {
            commentsViewModel.likeComment(commentId)
        }
    }
    
    fun unlikeComment(commentId: Int) {
        viewModelScope.launch {
            commentsViewModel.unlikeComment(commentId)
        }
    }
    
    fun createComment(
        content: String,
        parentCommentId: Int? = null,
        replyUserId: Int? = null,
        replyCommentId: Int? = null
    ) {
        viewModelScope.launch {
            commentsViewModel.createComment(
                content = content,
                parentCommentId = parentCommentId,
                replyUserId = replyUserId,
                replyCommentId = replyCommentId
            )
        }
    }
    
    fun deleteComment(commentId: Int) {
        commentsViewModel.deleteComment(commentId)
    }
}

// 新闻评论弹窗
// @param postId 新闻帖子ID
// @param commentCount 评论数量
// @param onDismiss 关闭回调

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewsCommentModal(
    postId: Int? = null,
    commentCount: Int = 0,
    onDismiss: () -> Unit = {},
    onCommentAdded: () -> Unit = {},
    onCommentDeleted: () -> Unit = {}
) {
    val AppColors = LocalAppTheme.current
    val navController = LocalNavController.current
    val debouncedNavigation = rememberDebouncedNavigation()
    
    // 实时评论数状态
    var currentCommentCount by remember { mutableStateOf(commentCount) }
    
    val model = viewModel<NewsCommentModalViewModel>(
        key = "NewsCommentModalViewModel_$postId",
        factory = object : ViewModelProvider.Factory {
            override fun <T : ViewModel> create(modelClass: Class<T>): T {
                return NewsCommentModalViewModel(postId) as T
            }
        }
    )
    
    val commentViewModel = model.commentsViewModel
    var navBarHeight = WindowInsets.navigationBars.asPaddingValues().calculateBottomPadding()
    
    var showCommentMenu by remember { mutableStateOf(false) }
    var contextComment by remember { mutableStateOf<CommentEntity?>(null) }
    var replyComment by remember { mutableStateOf<CommentEntity?>(null) }
    
    // 菜单弹窗
    if (showCommentMenu) {
        ModalBottomSheet(
            onDismissRequest = {
                showCommentMenu = false
            },
            containerColor = AppColors.background,
            sheetState = rememberModalBottomSheetState(
                skipPartiallyExpanded = true
            ),
            dragHandle = {},
            shape = RoundedCornerShape(topStart = 16.dp, topEnd = 16.dp),
        ) {
            CommentMenuModal(
                onDeleteClick = {
                    showCommentMenu = false
                    contextComment?.let {
                        model.deleteComment(it.id)
                        onCommentDeleted()
                        currentCommentCount = (currentCommentCount - 1).coerceAtLeast(0)
                    }
                },
                commentEntity = contextComment,
                onCloseClick = {
                    showCommentMenu = false
                },
                isSelf = AppState.UserId?.toLong() == contextComment?.author,
                onLikeClick = {
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.LIKE_MOMENT)) {
                        debouncedNavigation {
                            navController.navigate(NavigationRoute.Login.route)
                        }
                    } else {
                        showCommentMenu = false
                        contextComment?.let {
                            if (it.liked) {
                                model.unlikeComment(it.id)
                            } else {
                                model.likeComment(it.id)
                            }
                        }
                    }
                },
                onReplyClick = {
                    if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                        debouncedNavigation {
                            navController.navigate(NavigationRoute.Login.route)
                        }
                    } else {
                        showCommentMenu = false
                        replyComment = contextComment
                    }
                }
            )
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(AppColors.background)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 16.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = stringResource(R.string.comment_count, currentCommentCount),
                fontSize = 15.sp,
                fontWeight = FontWeight.Bold,
                color = AppColors.text
            )

            // 排序选择
            Row(
                modifier = Modifier
                    .fillMaxWidth(),
                horizontalArrangement = Arrangement.End
            ) {
                OrderSelectionComponent {
                    commentViewModel.order = it
                    commentViewModel.reloadComment()
                }
            }
        }

        // 评论列表
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f)
        ) {
            val isCommentListEmpty = !commentViewModel.isLoading &&
                currentCommentCount == 0 &&
                commentViewModel.commentsList.isEmpty() &&
                commentViewModel.addedCommentList.isEmpty()

            if (isCommentListEmpty) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(bottom = 32.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Image(
                        painter = painterResource(id = R.mipmap.invalid_name_3),
                        contentDescription = null,
                        modifier = Modifier
                            .width(160.dp)
                            .height(130.dp)
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = stringResource(R.string.news_no_comments),
                        fontSize = 15.sp,
                        color = AppColors.text
                    )
                }
            } else {
                LazyColumn {
                    item {
                        CommentContent(
                            viewModel = commentViewModel,
                            onLongClick = { comment ->
                                showCommentMenu = true
                                contextComment = comment
                            },
                            onReply = { parentComment, _, _, _ ->
                                if (GuestLoginCheckOut.needLogin(GuestLoginCheckOutScene.COMMENT_MOMENT)) {
                                    debouncedNavigation {
                                        navController.navigate(NavigationRoute.Login.route)
                                    }
                                } else {
                                    replyComment = parentComment
                                }
                            }
                        )
                    }
                }
            }
        }
        
        // 底部输入栏
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .background(AppColors.background)
        ) {
            HorizontalDivider(color = AppColors.inputBackground)
            
            EditCommentBottomModal(
                replyComment = replyComment,
                autoFocus = false
            ) {
                if (replyComment != null) {
                    if (replyComment?.parentCommentId != null) {
                        // 第三级评论
                        model.createComment(
                            content = it,
                            parentCommentId = replyComment?.parentCommentId,
                            replyUserId = replyComment?.author?.toInt(),
                            replyCommentId = replyComment?.id
                        )
                    } else {
                        // 子级评论
                        model.createComment(
                            content = it,
                            parentCommentId = replyComment?.id,
                            replyCommentId = replyComment?.id
                        )
                    }
                } else {
                    // 顶级评论
                    model.createComment(content = it)
                }
                replyComment = null
                onCommentAdded()
                currentCommentCount++
            }
            
            Spacer(modifier = Modifier.height(navBarHeight))
        }
    }
}
  