package xyz.magicalbits.smsremote.conversation

import androidx.compose.runtime.toMutableStateList
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import xyz.magicalbits.smsremote.network.NetworkClient

class ConversationViewModel : ViewModel() {
    private var remotePhoneNumber: String = ""
    private val _conversationData = MutableLiveData<ConversationScreenState>()
    val conversationData: LiveData<ConversationScreenState> = _conversationData

    fun setConversationData(phoneNumber: String?) {
        if (phoneNumber != null) {
            this.remotePhoneNumber = phoneNumber

            var messageDtoList: List<NetworkClient.SmsMessageDto> = listOf()
            viewModelScope.launch {
                val networkClient = NetworkClient()
                messageDtoList = networkClient.getSmsMessagesByLocalPhoneNumber(phoneNumber)
            }.invokeOnCompletion {
                _conversationData.value =
                    ConversationScreenState(
                        remotePhoneNumber = this.remotePhoneNumber,
                        initialMessages = messageDtoList.map {
                            Message(
                                if (it.msg_type == "INCOMING") {
                                    it.remote_phone_number
                                } else {
                                    it.local_phone_number
                                },
                                it.content,
                                // FIXME convert to HH:MM AM/PM
                                it.ts_sent.toString(),
                                null,
                            )
                        },
                    )
                println("sims live: ${_conversationData.value!!.initialMessages}")
            }
        }
    }
}

data class ConversationScreenState(
    val remotePhoneNumber: String,
    val initialMessages: List<Message>,
) {
    private val _messages: MutableList<Message> = initialMessages.toMutableStateList()

    val messages: List<Message> = _messages

    fun addMessage(msg: Message) {
        _messages.add(0, msg)
    }
}
