package com.aiosman.riderpro.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 androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.cachedIn
import androidx.paging.filter
import androidx.paging.map
import com.aiosman.riderpro.data.CommentRemoteDataSource
import com.aiosman.riderpro.data.CommentService
import com.aiosman.riderpro.data.CommentServiceImpl
import com.aiosman.riderpro.entity.CommentEntity
import com.aiosman.riderpro.entity.CommentPagingSource
import com.aiosman.riderpro.ui.index.tabs.moment.MomentViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class CommentsViewModel(
    var postId: String = 0.toString(),
) : ViewModel() {
    var commentService: CommentService = CommentServiceImpl()
    private var _commentsFlow = MutableStateFlow<PagingData<CommentEntity>>(PagingData.empty())
    val commentsFlow = _commentsFlow.asStateFlow()
    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)

    /**
     * 预加载，在跳转到 PostScreen 之前设置好内容
     */
    fun preTransit() {
        viewModelScope.launch {
            Pager(config = PagingConfig(pageSize = 5, enablePlaceholders = false),
                pagingSourceFactory = {
                    CommentPagingSource(
                        CommentRemoteDataSource(commentService),
                        postId = postId.toInt()
                    )
                }).flow.cachedIn(viewModelScope).collectLatest {
                _commentsFlow.value = it
            }
        }
    }

    /**
     * 加载评论
     */
    fun reloadComment() {
        viewModelScope.launch {
            try {
                Pager(config = PagingConfig(pageSize = 20, enablePlaceholders = false),
                    pagingSourceFactory = {
                        CommentPagingSource(
                            CommentRemoteDataSource(commentService),
                            postId = postId.toInt(),
                            order = order
                        )
                    }).flow.cachedIn(viewModelScope).collectLatest {
                    _commentsFlow.value = it
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }


    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) {
        val currentPagingData = commentsFlow.value
        val updatedPagingData = currentPagingData.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
                    }
                })
            }
        }
        _commentsFlow.value = updatedPagingData
    }

    /**
     * 点赞评论
     */
    suspend fun likeComment(commentId: Int) {
        try {
            commentService.likeComment(commentId)
            // 更新addCommentList
            if (updateHighlightCommentLike(commentId, true)) {
                return
            }
            if (updateAddedCommentLike(commentId, true)) {
                return
            }
            updateCommentLike(commentId, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    // 取消点赞评论
    suspend fun unlikeComment(commentId: Int) {
        commentService.dislikeComment(commentId)
        // 更新高亮评论点赞状态
        if (updateHighlightCommentLike(commentId, false)) {
            return
        }
        // 更新添加的评论点赞状态
        if (updateAddedCommentLike(commentId, false)) {
            return
        }
        // 更新评论点赞状态
        updateCommentLike(commentId, false)
    }

    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
            )
        MomentViewModel.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 {
                val currentPagingData = commentsFlow.value
                val updatedPagingData = currentPagingData.filter { it.id != commentId }
                _commentsFlow.value = updatedPagingData
            }
        }
    }

    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 {
                val currentPagingData = commentsFlow.value
                val updatedPagingData = currentPagingData.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
                }
                _commentsFlow.value = updatedPagingData
            }
        }

    }
}