package com.aiosman.ravenow.ui.index.tabs.message.tab

import android.content.Context
import android.icu.util.Calendar
import android.util.Log
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.NavHostController
import com.aiosman.ravenow.AppState
import com.aiosman.ravenow.ConstVars
import com.aiosman.ravenow.data.UserService
import com.aiosman.ravenow.data.UserServiceImpl
import com.aiosman.ravenow.exp.formatChatTime
import com.aiosman.ravenow.ui.NavigationRoute
import com.aiosman.ravenow.ui.navigateToChat
// OpenIM SDK 导入
import com.aiosman.ravenow.AppStore
import com.aiosman.ravenow.data.api.ApiClient
import io.openim.android.sdk.OpenIMClient
import io.openim.android.sdk.listener.OnBase
import io.openim.android.sdk.models.ConversationInfo
import io.openim.android.sdk.models.Message
import kotlinx.coroutines.launch
import kotlin.coroutines.suspendCoroutine
import com.aiosman.ravenow.utils.MessageParser
import com.aiosman.ravenow.data.repo.TrtcUserTypeRepository

data class FriendConversation(
    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 {
        fun convertToFriendConversation(conversation: ConversationInfo, context: Context): FriendConversation {
            val lastMessage = Calendar.getInstance().apply {
                timeInMillis = conversation.latestMsgSendTime
            }
            
            // 解析最新消息
            val (displayText, isSelf) = MessageParser.parseLatestMessage(conversation.latestMsg)
            
            return FriendConversation(
                id = conversation.conversationID,
                nickname = conversation.showName ?: "",
                lastMessage = displayText, // 使用解析后的显示文本
                lastMessageTime = lastMessage.time.formatChatTime(context),
                avatar = "${ApiClient.BASE_API_URL+"/"}${conversation.faceURL}"+"?token="+"${AppStore.token}".replace("storage/avatars/", "/avatar/"),
                unreadCount = conversation.unreadCount,
                trtcUserId = conversation.userID ?: "",
                displayText = displayText,
                isSelf = isSelf // 使用解析后的发送者信息
            )
        }
    }
}

object FriendChatListViewModel : ViewModel() {
    val userService: UserService = UserServiceImpl()
    var friendChatList by mutableStateOf<List<FriendConversation>>(emptyList())
    var isLoading by mutableStateOf(false)
    var refreshing by mutableStateOf(false)
    var hasNext by mutableStateOf(true)
    var currentPage by mutableStateOf(1)
    var error by mutableStateOf<String?>(null)

    // 计算朋友总未读消息数
    val totalUnreadCount: Int
        get() = friendChatList.sumOf { it.unreadCount }

    private val pageSize = 20

    fun refreshPager(pullRefresh: Boolean = false, context: Context? = null) {
        if (isLoading && !pullRefresh) return
        viewModelScope.launch {
            try {
                isLoading = true
                refreshing = pullRefresh
                error = null
                context?.let { loadFriendChatList(it) }
                currentPage = 1
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            } finally {
                isLoading = false
                refreshing = false
            }
        }
    }

    fun loadMore() {
        if (isLoading || !hasNext) return
        viewModelScope.launch {
            try {
                isLoading = true
                error = null
                // 腾讯IM的会话列表是一次性获取的，这里模拟分页
                // 实际项目中可能需要根据时间戳或其他方式实现真正的分页
                hasNext = false
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            } finally {
                isLoading = false
            }
        }
    }

    private suspend fun loadFriendChatList(context: Context) {
        // 检查 OpenIM 是否已登录
        if (!com.aiosman.ravenow.AppState.enableChat) {
            android.util.Log.w("FriendChatListViewModel", "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")))
                    }
                }
            )
        }

        // 仅单聊
        val singleChats = result.filter { it.conversationType == 1 }
        val trtcIds = singleChats.mapNotNull { it.userID }.distinct()
        // 预热缓存（包含AI）
        try {
            TrtcUserTypeRepository.ensureTypes(context, trtcIds)
        } catch (e: Exception) {
            Log.w("FriendChatListViewModel", "ensureTypes failed: ${e.message}")
        }
        // 过滤出普通人会话（未知也归入普通人以回退）
        val filteredConversations = singleChats.filter { conversation ->
            val id = conversation.userID ?: return@filter true
            TrtcUserTypeRepository.getCachedType(id) != true
        }

        friendChatList = filteredConversations.map { conversation ->
            FriendConversation.convertToFriendConversation(conversation, context)
        }
    }

    fun goToChat(
        conversation: FriendConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId,0)
                navController.navigateToChat(profile.id.toString())
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun goToUserDetail(
        conversation: FriendConversation,
        navController: NavHostController
    ) {
        viewModelScope.launch {
            try {
                val profile = userService.getUserProfileByTrtcUserId(conversation.trtcUserId,0)
                navController.navigate(
                    NavigationRoute.AccountProfile.route.replace(
                        "{id}",
                        profile.id.toString()
                    )
                )
            } catch (e: Exception) {
                error = ""
                e.printStackTrace()
            }
        }
    }

    fun refreshConversation(context: Context, userId: String) {
        viewModelScope.launch {
            loadFriendChatList(context)
        }
    }
}
