package com.aiosman.riderpro.ui.chat

import android.content.Context
import android.net.Uri
import android.provider.MediaStore
import android.util.Log
import android.webkit.MimeTypeMap
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.riderpro.ChatState
import com.aiosman.riderpro.data.AccountService
import com.aiosman.riderpro.data.AccountServiceImpl
import com.aiosman.riderpro.data.UserService
import com.aiosman.riderpro.data.UserServiceImpl
import com.aiosman.riderpro.entity.AccountProfileEntity
import com.aiosman.riderpro.entity.ChatItem
import com.aiosman.riderpro.entity.ChatNotification
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener
import com.tencent.imsdk.v2.V2TIMCallback
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMMessage
import com.tencent.imsdk.v2.V2TIMSendCallback
import com.tencent.imsdk.v2.V2TIMValueCallback
import kotlinx.coroutines.launch
import java.io.File
import java.io.FileOutputStream
import java.io.InputStream


class ChatViewModel(
    val userId: String,
) : ViewModel() {
    var chatData by mutableStateOf<List<ChatItem>>(emptyList())
    var userProfile by mutableStateOf<AccountProfileEntity?>(null)
    var myProfile by mutableStateOf<AccountProfileEntity?>(null)
    val userService: UserService = UserServiceImpl()
    val accountService: AccountService = AccountServiceImpl()
    var textMessageListener: V2TIMAdvancedMsgListener? = null
    var hasMore by mutableStateOf(true)
    var isLoading by mutableStateOf(false)
    var lastMessage: V2TIMMessage? = null
    val showTimestampMap = mutableMapOf<String, Boolean>() // Add this map
    var chatNotification by mutableStateOf<ChatNotification?>(null)
    var goToNew by mutableStateOf(false)
    fun init(context: Context) {
        // 获取用户信息
        viewModelScope.launch {
            val resp = userService.getUserProfile(userId)
            userProfile = resp
            myProfile = accountService.getMyAccountProfile()

            RegistListener(context)
            fetchHistoryMessage(context)
            // 获取通知信息
            val notiStrategy = ChatState.getStrategyByTargetTrtcId(resp.trtcUserId)
            chatNotification = notiStrategy
        }
    }


    fun RegistListener(context: Context) {
        textMessageListener = object : V2TIMAdvancedMsgListener() {
            override fun onRecvNewMessage(msg: V2TIMMessage?) {
                super.onRecvNewMessage(msg)
                msg?.let {
                    val chatItem = ChatItem.convertToChatItem(msg, context)
                    chatItem?.let {
                        chatData = listOf(it) + chatData
                        goToNew = true
                    }
                }
            }
        }
        V2TIMManager.getMessageManager().addAdvancedMsgListener(textMessageListener);
    }

    fun UnRegistListener() {
        V2TIMManager.getMessageManager().removeAdvancedMsgListener(textMessageListener);
    }

    fun clearUnRead() {
        val conversationID = "c2c_${userProfile?.trtcUserId}"
        V2TIMManager.getConversationManager()
            .cleanConversationUnreadMessageCount(conversationID, 0, 0, object : V2TIMCallback {
                override fun onSuccess() {
                    Log.i("imsdk", "success")
                }

                override fun onError(code: Int, desc: String) {
                    Log.i("imsdk", "failure, code:$code, desc:$desc")
                }
            })
    }


    fun onLoadMore(context: Context) {
        if (!hasMore || isLoading) {
            return
        }
        isLoading = true
        viewModelScope.launch {
            V2TIMManager.getMessageManager().getC2CHistoryMessageList(
                userProfile?.trtcUserId!!,
                20,
                lastMessage,
                object : V2TIMValueCallback<List<V2TIMMessage>> {
                    override fun onSuccess(p0: List<V2TIMMessage>?) {
                        chatData = chatData + (p0 ?: emptyList()).map {
                            ChatItem.convertToChatItem(it, context)
                        }.filterNotNull()
                        if ((p0?.size ?: 0) < 20) {
                            hasMore = false
                        }
                        lastMessage = p0?.lastOrNull()
                        isLoading = false
                        Log.d("ChatViewModel", "fetch history message success")
                    }

                    override fun onError(p0: Int, p1: String?) {
                        Log.e("ChatViewModel", "fetch history message error: $p1")
                        isLoading = false
                    }
                }
            )
        }
    }

    fun sendMessage(message: String, context: Context) {
        V2TIMManager.getInstance().sendC2CTextMessage(
            message,
            userProfile?.trtcUserId!!,
            object : V2TIMSendCallback<V2TIMMessage> {
                override fun onProgress(p0: Int) {

                }

                override fun onError(p0: Int, p1: String?) {
                    Log.e("ChatViewModel", "send message error: $p1")
                }

                override fun onSuccess(p0: V2TIMMessage?) {
                    Log.d("ChatViewModel", "send message success")
                    val chatItem = ChatItem.convertToChatItem(p0!!, context)
                    chatItem?.let {
                        chatData = listOf(it) + chatData
                        goToNew = true
                    }
                }
            }
        )
    }

    fun sendImageMessage(imageUri: Uri, context: Context) {
        val tempFile = createTempFile(context, imageUri)
        val imagePath = tempFile?.path
        if (imagePath != null) {
            val v2TIMMessage = V2TIMManager.getMessageManager().createImageMessage(imagePath)
            V2TIMManager.getMessageManager().sendMessage(
                v2TIMMessage,
                userProfile?.trtcUserId!!,
                null,
                V2TIMMessage.V2TIM_PRIORITY_NORMAL,
                false,
                null,
                object : V2TIMSendCallback<V2TIMMessage> {
                    override fun onProgress(p0: Int) {
                        Log.d("ChatViewModel", "send image message progress: $p0")
                    }

                    override fun onError(p0: Int, p1: String?) {
                        Log.e("ChatViewModel", "send image message error: $p1")
                    }

                    override fun onSuccess(p0: V2TIMMessage?) {
                        Log.d("ChatViewModel", "send image message success")
                        val chatItem = ChatItem.convertToChatItem(p0!!, context)
                        chatItem?.let {
                            chatData = listOf(it) + chatData
                            goToNew = true
                        }
                    }
                }
            )
        }

    }

    fun createTempFile(context: Context, uri: Uri): File? {
        return try {
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = context.contentResolver.query(uri, projection, null, null, null)
            cursor?.use {
                if (it.moveToFirst()) {
                    val columnIndex = it.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    val filePath = it.getString(columnIndex)
                    val inputStream: InputStream? = context.contentResolver.openInputStream(uri)
                    val mimeType = context.contentResolver.getType(uri)
                    val extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType)
                    val tempFile =
                        File.createTempFile("temp_image", ".$extension", context.cacheDir)
                    val outputStream = FileOutputStream(tempFile)

                    inputStream?.use { input ->
                        outputStream.use { output ->
                            input.copyTo(output)
                        }
                    }
                    tempFile
                } else {
                    null
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            null
        }
    }

    fun fetchHistoryMessage(context: Context) {
        V2TIMManager.getMessageManager().getC2CHistoryMessageList(
            userProfile?.trtcUserId!!,
            20,
            null,
            object : V2TIMValueCallback<List<V2TIMMessage>> {
                override fun onSuccess(p0: List<V2TIMMessage>?) {
                    chatData = (p0 ?: emptyList()).mapNotNull {
                        ChatItem.convertToChatItem(it, context)
                    }
                    if ((p0?.size ?: 0) < 20) {
                        hasMore = false
                    }
                    lastMessage = p0?.lastOrNull()
                    Log.d("ChatViewModel", "fetch history message success")
                }

                override fun onError(p0: Int, p1: String?) {
                    Log.e("ChatViewModel", "fetch history message error: $p1")
                }
            }
        )
    }

    fun getDisplayChatList(): List<ChatItem> {
        val list = chatData
        // Update showTimestamp for each message
        for (item in list) {
            item.showTimestamp = showTimestampMap.getOrDefault(item.msgId, false)
        }
        return list
    }

    suspend fun updateNotificationStrategy(strategy: String) {
        userProfile?.let {
            val result = ChatState.updateChatNotification(it.id, strategy)
            chatNotification = result
        }
    }

    val notificationStrategy get() = chatNotification?.strategy ?: "default"
}