package com.aiosman.ravenow.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.ravenow.AppState
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.AccountNotice
import com.aiosman.ravenow.data.AccountService
import com.aiosman.ravenow.data.AccountServiceImpl
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.entity.CommentEntity
import com.aiosman.ravenow.exp.formatChatTime
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.navigateToChat
import com.aiosman.ravenow.utils.TrtcHelper
// OpenIM SDK 导入
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.models.ConversationInfo
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine

data class Conversation(
    val id: String,
    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
) {
    companion object {
        // TODO: 如果需要使用 Conversation 数据类，可以实现 OpenIM 版本的 convertToConversation 方法
        // fun convertToConversation(conversation: ConversationInfo, context: Context): Conversation {
        //     // OpenIM 版本的转换逻辑
        // }
    }
}

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, loadChat: Boolean = false) {
//        if (loadChat) {
//            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) {
        // 检查 OpenIM 是否已登录
        if (!com.aiosman.ravenow.AppState.enableChat) {
            android.util.Log.w("MessageListViewModel", "OpenIM 未登录，跳过加载聊天列表")
            return
        }
        
        val result = suspendCoroutine { continuation ->
            // OpenIM 获取所有会话列表
            OpenIMClient.getInstance().conversationManager.getAllConversationList(
                object : OnBase<List<ConversationInfo>> {
                    override fun onSuccess(data: List<ConversationInfo>?) {
                        continuation.resumeWith(Result.success(data ?: emptyList()))
                    }

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

        // 暂时注释掉，因为 convertToConversation 方法已被注释
        // chatList = result.map { conversation ->
        //     Conversation.convertToConversation(conversation, context)
        // }
    }

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


}