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.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.MomentService
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.AccountProfileEntity
import com.aiosman.ravenow.entity.MomentEntity
import com.aiosman.ravenow.entity.MomentServiceImpl
import com.aiosman.ravenow.event.FollowChangeEvent
import com.aiosman.ravenow.event.MomentFavouriteChangeEvent
import com.aiosman.ravenow.event.MomentLikeChangeEvent
import com.aiosman.ravenow.event.MomentRemoveEvent
import com.aiosman.ravenow.ui.index.tabs.moment.tabs.timeline.TimelineMomentViewModel
import com.aiosman.ravenow.ui.index.tabs.profile.MyProfileViewModel
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe


class PostViewModel(
    val postId: String
) : ViewModel() {
    var service: MomentService = MomentServiceImpl()
    var userService: UserService = UserServiceImpl()


    var accountProfileEntity by mutableStateOf<AccountProfileEntity?>(null)
    var moment by mutableStateOf<MomentEntity?>(null)
    var accountService: AccountService = AccountServiceImpl()
    var commentsViewModel: CommentsViewModel = CommentsViewModel(postId)
    var isError by mutableStateOf(false)
    var isFirstLoad by mutableStateOf(true)
    init {
        EventBus.getDefault().register(this)
    }

    fun reloadComment() {
        commentsViewModel.reloadComment()
    }

    suspend fun initData(highlightCommentId: Int? = null) {
        if (!isFirstLoad) {
            return
        }
        isFirstLoad = false
        try {
            moment = service.getMomentById(postId.toInt())
        } catch (e: Exception) {
            isError = true
            return
        }
        highlightCommentId?.let {
            commentsViewModel.highlightComment(it)
        }
        commentsViewModel.reloadComment()

    }

    suspend fun likeComment(commentId: Int) {
        commentsViewModel.likeComment(commentId)
    }

    suspend fun unlikeComment(commentId: Int) {
        commentsViewModel.unlikeComment(commentId)
    }

    suspend fun createComment(
        content: String,
        parentCommentId: Int? = null,
        replyUserId: Int? = null,
        replyCommentId: Int? = null
    ) {
        commentsViewModel.createComment(
            content = content,
            parentCommentId = parentCommentId,
            replyUserId = replyUserId,
            replyCommentId = replyCommentId
        )
        moment = moment?.copy(commentCount = moment?.commentCount?.plus(1) ?: 0)
    }

    @Subscribe
    fun onMomentLikeChangeEvent(event: MomentLikeChangeEvent) {
        moment?.let {
            if (event.postId == it.id) {
                moment = it.copy(likeCount = event.likeCount ?: it.likeCount, liked = event.isLike)
            }
        }
    }

    suspend fun likeMoment() {
        moment?.let {
            service.likeMoment(it.id)
            EventBus.getDefault().post(
                MomentLikeChangeEvent(
                    postId = it.id,
                    likeCount = it.likeCount + 1,
                    isLike = true
                )
            )
        }
    }

    suspend fun dislikeMoment() {
        moment?.let {
            service.dislikeMoment(it.id)
            EventBus.getDefault().post(
                MomentLikeChangeEvent(
                    postId = it.id,
                    likeCount = it.likeCount - 1,
                    isLike = false
                )
            )
        }
    }

    @Subscribe
    fun onMomentFavouriteChangeEvent(event: MomentFavouriteChangeEvent) {
        moment?.let {
            if (event.postId == it.id) {
                val favouriteCount = if (event.isFavourite) {
                    it.favoriteCount + 1
                } else {
                    it.favoriteCount - 1
                }
                moment = it.copy(
                    favoriteCount = favouriteCount,
                    isFavorite = event.isFavourite
                )
            }
        }
    }

    suspend fun favoriteMoment() {
        moment?.let {
            service.favoriteMoment(it.id)
            EventBus.getDefault().post(
                MomentFavouriteChangeEvent(
                    postId = it.id,
                    isFavourite = true
                )
            )
        }
    }

    suspend fun unfavoriteMoment() {
        moment?.let {
            service.unfavoriteMoment(it.id)
            EventBus.getDefault().post(
                MomentFavouriteChangeEvent(
                    postId = it.id,
                    isFavourite = false
                )
            )

        }
    }

    suspend fun followUser() {
        moment?.let {
            userService.followUser(it.authorId.toString())
            moment = moment?.copy(followStatus = true)
            // 发送关注事件，通知动态列表更新关注状态
            EventBus.getDefault().post(FollowChangeEvent(it.authorId, true))
        }
    }

    suspend fun unfollowUser() {
        moment?.let {
            userService.unFollowUser(it.authorId.toString())
            moment = moment?.copy(followStatus = false)
            // 发送取消关注事件，通知动态列表更新关注状态
            EventBus.getDefault().post(FollowChangeEvent(it.authorId, false))
        }
    }

    fun deleteComment(commentId: Int) {
        commentsViewModel.deleteComment(commentId)
        moment = moment?.copy(commentCount = moment?.commentCount?.minus(1) ?: 0)
        moment?.let {
        }
    }

    var avatar: String? = null
        get() {
            accountProfileEntity?.avatar?.let {
                return it
            }
            moment?.avatar?.let {
                return it
            }
            return field
        }
    var nickname: String? = null
        get() {
            accountProfileEntity?.nickName?.let {
                return it
            }
            moment?.nickname?.let {
                return it
            }
            return field
        }

    fun deleteMoment(callback: () -> Unit) {
        viewModelScope.launch {
            moment?.let {
                service.deleteMoment(it.id)
                EventBus.getDefault().post(MomentRemoveEvent(it.id))
            }
            callback()
        }
    }

    fun loadMoreSubComments(commentId: Int) {
        commentsViewModel.loadMoreSubComments(commentId)
    }

    override fun onCleared() {
        super.onCleared()
        EventBus.getDefault().unregister(this)
    }
}