package xyz.magicalbits.smsremote.sim

import androidx.compose.runtime.Immutable
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 SimViewModel : ViewModel() {
    private var simPhoneNumber: String = ""
    private val _simConversations = MutableLiveData<SimScreenState>()
    val simData: LiveData<SimScreenState> = _simConversations

    fun setSimData(phoneNumber: String?) {
        if (phoneNumber != null) {
            simPhoneNumber = phoneNumber

            var conversationDtoList: List<NetworkClient.ConversationPreviewDto> = listOf()
            // TODO uncomment after adding the corresponding API endpoint
//            viewModelScope.launch {
//                val networkClient = NetworkClient()
//                conversationDtoList = networkClient.getConversationPreviews(simPhoneNumber)
//                println("conv previews: $conversationDtoList")
//            }.invokeOnCompletion {
//                _simConversations.value =
//                    SimScreenState(
//                        phoneNumber = simPhoneNumber,
//                        conversations = conversationDtoList.map { convertFromDto(it) }.toList()
//                    )
//            }
        }
    }
}

fun convertFromDto(conversation: NetworkClient.ConversationPreviewDto): ConversationRowState {
    return ConversationRowState(
        phoneNumber = conversation.remote_phone_number,
        lastMessage = conversation.last_message_content,
        messageTimestamp = conversation.message_timestamp,
    )
}

@Immutable
data class SimScreenState(
    val phoneNumber: String,
    val conversations: List<ConversationRowState>,
)

@Immutable
data class ConversationRowState(
    val phoneNumber: String,
    val lastMessage: String,
    val messageTimestamp: Int,
)
