package com.aiosman.ravenow.ui.post

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aiosman.ravenow.data.CommentService
import com.aiosman.ravenow.data.CommentServiceImpl
import com.aiosman.ravenow.entity.CommentEntity
import kotlinx.coroutines.launch

class CommentsViewModel(
    var postId: String = 0.toString(),
) : ViewModel() {
    var commentService: CommentService = CommentServiceImpl()
    var commentsList by mutableStateOf<List<CommentEntity>>(emptyList())
    var order: String by mutableStateOf("like")
    var addedCommentList by mutableStateOf<List<CommentEntity>>(emptyList())
    var subCommentLoadingMap by mutableStateOf(mutableMapOf<Int, Boolean>())
    var highlightCommentId by mutableStateOf<Int?>(null)
    var highlightComment by mutableStateOf<CommentEntity?>(null)
    var isLoading by mutableStateOf(false)
    var hasError by mutableStateOf(false)

    /**
     * 预加载，在跳转到 PostScreen 之前设置好内容
     */
    fun preTransit() {
        viewModelScope.launch {
            try {
                isLoading = true
                val response = commentService.getComments(
                    pageNumber = 1,
                    postId = postId.toInt(),
                    pageSize = 10
                )
                commentsList = response.list
                hasError = false
            } catch (e: Exception) {
                e.printStackTrace()
                hasError = true
            } finally {
                isLoading = false
            }
        }
    }

    /**
     * 加载评论
     */
    fun reloadComment() {
        viewModelScope.launch {
            try {
                isLoading = true
                val response = commentService.getComments(
                    pageNumber = 1,
                    postId = postId.toInt(),
                    order = order,
                    pageSize = 50
                )
                commentsList = response.list
                hasError = false
            } catch (e: Exception) {
                e.printStackTrace()
                hasError = true
            } finally {
                isLoading = false
            }
        }
    }


    suspend fun highlightComment(commentId: Int) {
        highlightCommentId = commentId
        val resp = commentService.getCommentById(commentId)
        highlightComment = resp
    }

    /**
     * 更新高亮评论点赞状态
     */
    private fun updateHighlightCommentLike(commentId: Int, isLike: Boolean): Boolean {
        var isUpdate = false
        highlightComment?.let {
            if (it.id == commentId) {
                highlightComment =
                    it.copy(liked = isLike, likes = if (isLike) it.likes + 1 else it.likes - 1)
                isUpdate = true
            }
            highlightComment = it.copy(
                reply = it.reply.map { replyComment ->
                    if (replyComment.id == commentId) {
                        isUpdate = true
                        replyComment.copy(
                            liked = isLike,
                            likes = if (isLike) replyComment.likes + 1 else replyComment.likes - 1
                        )
                    } else {
                        replyComment
                    }
                }
            )
        }
        return isUpdate
    }

    /**
     * 更新添加的评论点赞状态
     */
    private fun updateAddedCommentLike(commentId: Int, isLike: Boolean): Boolean {
        var isUpdate = false
        addedCommentList = addedCommentList.map {
            if (it.id == commentId) {
                isUpdate = true
                it.copy(liked = isLike, likes = if (isLike) it.likes + 1 else it.likes - 1)
            } else {
                it
            }
        }
        return isUpdate
    }

    /**
     * 更新评论点赞状态
     */
    private fun updateCommentLike(commentId: Int, isLike: Boolean) {
        commentsList = commentsList.map { comment ->
            if (comment.id == commentId) {
                comment.copy(
                    liked = isLike,
                    likes = if (isLike) comment.likes + 1 else comment.likes - 1
                )
            } else {
                // 可能是回复的评论
                comment.copy(reply = comment.reply.map { replyComment ->
                    if (replyComment.id == commentId) {
                        replyComment.copy(
                            liked = isLike,
                            likes = if (isLike) replyComment.likes + 1 else replyComment.likes - 1
                        )
                    } else {
                        replyComment
                    }
                })
            }
        }
    }

    // 用于防止重复点赞的状态集合
    private val _pendingLikeOperations = mutableSetOf<Int>()

    /**
     * 点赞评论 - 使用乐观更新策略
     */
    suspend fun likeComment(commentId: Int) {
        // 防止重复操作
        if (_pendingLikeOperations.contains(commentId)) {
            return
        }
        
        _pendingLikeOperations.add(commentId)
        
        try {
            // 乐观更新：先更新UI状态
            val previousState = getCurrentCommentLikeState(commentId)
            updateCommentLikeState(commentId, true)
            
            // 然后调用API
            commentService.likeComment(commentId)
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果API调用失败，回滚UI状态
            updateCommentLikeState(commentId, false)
        } finally {
            _pendingLikeOperations.remove(commentId)
        }
    }

    /**
     * 取消点赞评论 - 使用乐观更新策略
     */
    suspend fun unlikeComment(commentId: Int) {
        // 防止重复操作
        if (_pendingLikeOperations.contains(commentId)) {
            return
        }
        
        _pendingLikeOperations.add(commentId)
        
        try {
            // 乐观更新：先更新UI状态
            val previousState = getCurrentCommentLikeState(commentId)
            updateCommentLikeState(commentId, false)
            
            // 然后调用API
            commentService.dislikeComment(commentId)
        } catch (e: Exception) {
            e.printStackTrace()
            // 如果API调用失败，回滚UI状态
            updateCommentLikeState(commentId, true)
        } finally {
            _pendingLikeOperations.remove(commentId)
        }
    }

    /**
     * 获取当前评论的点赞状态
     */
    private fun getCurrentCommentLikeState(commentId: Int): Boolean {
        // 检查高亮评论
        highlightComment?.let { comment ->
            if (comment.id == commentId) {
                return comment.liked
            }
            comment.reply.find { it.id == commentId }?.let { return it.liked }
        }
        
        // 检查添加的评论列表
        addedCommentList.find { it.id == commentId }?.let { return it.liked }
        
        // 检查分页数据（这里简化处理，实际项目中可能需要更复杂的逻辑）
        return false
    }

    /**
     * 统一的评论点赞状态更新方法
     */
    private fun updateCommentLikeState(commentId: Int, isLike: Boolean) {
        // 更新高亮评论点赞状态
        if (updateHighlightCommentLike(commentId, isLike)) {
            return
        }
        // 更新添加的评论点赞状态
        if (updateAddedCommentLike(commentId, isLike)) {
            return
        }
        // 更新评论点赞状态
        updateCommentLike(commentId, isLike)
    }

    suspend fun createComment(
        content: String,
        parentCommentId: Int? = null,
        replyUserId: Int? = null,
        replyCommentId: Int? = null
    ) {
        val comment =
            commentService.createComment(
                postId = postId.toInt(),
                content = content,
                parentCommentId = parentCommentId,
                replyUserId = replyUserId,
                replyCommentId = replyCommentId
            )
//        TimelineMomentViewModel.updateCommentCount(postId.toInt())
        // add to first
        addedCommentList = listOf(comment) + addedCommentList
    }

    fun deleteComment(commentId: Int) {
        viewModelScope.launch {
            commentService.DeleteComment(commentId)
            // 如果是刚刚创建的评论，则从addedCommentList中删除
            if (addedCommentList.any { it.id == commentId }) {
                addedCommentList = addedCommentList.filter { it.id != commentId }
            } else {
                commentsList = commentsList.filter { it.id != commentId }
            }
        }
    }

    fun loadMoreSubComments(commentId: Int) {
        if (highlightComment?.id == commentId) {
            // 高亮的评论,更新高亮评论的回复
            highlightComment?.let {
                viewModelScope.launch {
                    val subCommentList = commentService.getComments(
                        postId = postId.toInt(),
                        parentCommentId = commentId,
                        pageNumber = it.replyPage + 1,
                        pageSize = 3,
                    ).list
                    highlightComment = it.copy(
                        reply = it.reply.plus(subCommentList),
                        replyPage = it.replyPage + 1
                    )
                }
            }
        } else {
            // 普通评论
            viewModelScope.launch {
                commentsList = commentsList.map { comment ->
                    if (comment.id == commentId) {
                        try {
                            subCommentLoadingMap[commentId] = true
                            val subCommentList = commentService.getComments(
                                postId = postId.toInt(),
                                parentCommentId = commentId,
                                pageNumber = comment.replyPage + 1,
                                pageSize = 3,
                                order = "earliest"
                            ).list
                            return@map comment.copy(
                                reply = comment.reply.plus(subCommentList),
                                replyPage = comment.replyPage + 1
                            )
                        } catch (e: Exception) {
                            return@map comment.copy()
                        } finally {
                            subCommentLoadingMap[commentId] = false
                        }
                    }
                    comment
                }
            }
        }

    }
}