package com.aiosman.riderpro.ui.index.tabs.message

import android.content.Context
import android.icu.util.Calendar
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.navigation.NavController
import androidx.navigation.NavHostController
import androidx.paging.PagingData
import androidx.paging.map
import com.aiosman.riderpro.data.AccountNotice
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.entity.CommentEntity
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserService
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.exp.formatChatTime
import com.aiosman.riderpro.ui.NavigationRoute
import com.aiosman.riderpro.ui.index.tabs.profile.MyProfileViewModel
import com.aiosman.riderpro.ui.navigateToChat
import com.aiosman.riderpro.utils.TrtcHelper
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMValueCallback
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine

data class Conversation(
    val trtcUserId: String,
    val nickname: String,
    val lastMessage: String,
    val lastMessageTime: String,
    val avatar: String = "",
    val unreadCount: Int = 0,
    val displayText: String,
    val isSelf: Boolean
)

object MessageListViewModel : ViewModel() {
    val accountService: AccountService = AccountServiceImpl()
    val userService: UserService = UserServiceImpl()
    var noticeInfo by mutableStateOf<AccountNotice?>(null)
    var chatList by mutableStateOf<List<Conversation>>(emptyList())
    private val _commentItemsFlow = MutableStateFlow<PagingData<CommentEntity>>(PagingData.empty())
    var isLoading by mutableStateOf(false)
    var unReadConversationCount by mutableStateOf(0L)
    var isFirstLoad = true
    suspend fun initData(context: Context, force: Boolean = false) {
        loadChatList(context)
        loadUnreadCount()
        if (!isFirstLoad && !force) {
            return
        }
        if (force) {
            isLoading = true
        }
        isFirstLoad = false
        val info = accountService.getMyNoticeInfo()
        noticeInfo = info

        isLoading = false

    }

    val likeNoticeCount
        get() = noticeInfo?.likeCount ?: 0
    val followNoticeCount
        get() = noticeInfo?.followCount ?: 0
    val favouriteNoticeCount
        get() = noticeInfo?.favoriteCount ?: 0
    val commentNoticeCount
        get() = noticeInfo?.commentCount ?: 0

    private fun updateIsRead(id: Int) {
        val currentPagingData = _commentItemsFlow.value
        val updatedPagingData = currentPagingData.map { commentEntity ->
            if (commentEntity.id == id) {
                commentEntity.copy(unread = false)
            } else {
                commentEntity
            }
        }
        _commentItemsFlow.value = updatedPagingData
    }


    fun clearLikeNoticeCount() {
        noticeInfo = noticeInfo?.copy(likeCount = 0)
    }

    fun clearFollowNoticeCount() {
        noticeInfo = noticeInfo?.copy(followCount = 0)
    }

    fun clearFavouriteNoticeCount() {
        noticeInfo = noticeInfo?.copy(favoriteCount = 0)
    }

    fun updateUnReadCount(delta: Int) {
        noticeInfo?.let {
            noticeInfo = it.copy(commentCount = it.commentCount + delta)
        }
    }

    fun ResetModel() {
        _commentItemsFlow.value = PagingData.empty()
        noticeInfo = null
        isLoading = false
        isFirstLoad = true
    }

    suspend fun loadChatList(context: Context) {
        val result = suspendCoroutine { continuation ->
            V2TIMManager.getConversationManager().getConversationList(
                0,
                Int.MAX_VALUE,
                object : V2TIMValueCallback<V2TIMConversationResult> {
                    override fun onSuccess(t: V2TIMConversationResult?) {
                        continuation.resumeWith(Result.success(t))
                    }

                    override fun onError(code: Int, desc: String?) {
                        continuation.resumeWith(Result.failure(Exception("Error $code: $desc")))
                    }
                }
            )
        }

        chatList = result?.conversationList?.map { msg: V2TIMConversation ->
            val lastMessage = Calendar.getInstance().apply {
                timeInMillis = msg.lastMessage?.timestamp ?: 0
                timeInMillis *= 1000
            }
            var displayText = ""
            when (msg.lastMessage?.elemType) {
                V2TIMMessage.V2TIM_ELEM_TYPE_TEXT -> {
                    displayText = msg.lastMessage?.textElem?.text ?: ""
                }
                V2TIMMessage.V2TIM_ELEM_TYPE_IMAGE -> {
                    displayText = "[图片]"
                }
            }
            Conversation(
                nickname = msg.showName,
                lastMessage = msg.lastMessage?.textElem?.text ?: "",
                lastMessageTime = lastMessage.time.formatChatTime(context),
                avatar = msg.faceUrl,
                unreadCount = msg.unreadCount,
                trtcUserId = msg.userID,
                displayText = displayText,
                isSelf = msg.lastMessage.sender == MyProfileViewModel.profile?.trtcUserId
            )
        } ?: emptyList()
    }

    suspend fun loadUnreadCount() {
        try {
            this.unReadConversationCount = TrtcHelper.loadUnreadCount()
        } catch (e: Exception) {
            e.printStackTrace()
            this.unReadConversationCount = 0
        }
    }

    fun goToChat(
        conversation: Conversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId)
            navController.navigateToChat(profile.id.toString())
        }
    }

    fun goToUserDetail(
        conversation: Conversation,
        navController: NavController
    ) {
        viewModelScope.launch {
            val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId)
            navController.navigate(NavigationRoute.AccountProfile.route.replace("{id}", profile.id.toString()))
        }
    }

}