package de.krisenvorrat.app.ui.messaging

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import de.krisenvorrat.app.data.db.entity.MessageEntity
import de.krisenvorrat.app.domain.repository.MessageRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

internal data class ChatUiState(
    val messages: List<MessageEntity> = emptyList(),
    val myUserId: String = "",
    val recipientUsername: String = "",
    val inputText: String = "",
    val isSending: Boolean = false
)

@HiltViewModel
internal class ChatViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val messageRepository: MessageRepository
) : ViewModel() {

    private val recipientId: String = savedStateHandle.get<String>("recipientId") ?: ""
    private val recipientUsername: String = savedStateHandle.get<String>("recipientUsername") ?: ""

    private val _uiState = MutableStateFlow(ChatUiState(recipientUsername = recipientUsername))
    val uiState: StateFlow<ChatUiState> = _uiState

    init {
        viewModelScope.launch {
            val myId = messageRepository.getMyUserId() ?: ""
            _uiState.update { it.copy(myUserId = myId) }
            if (myId.isNotEmpty()) {
                messageRepository.getConversation(myId, recipientId).collect { messages ->
                    _uiState.update { it.copy(messages = messages) }
                }
            }
        }
    }

    fun onInputChanged(text: String) {
        _uiState.update { it.copy(inputText = text) }
    }

    fun sendMessage() {
        val text = _uiState.value.inputText.trim()
        if (text.isEmpty()) return
        viewModelScope.launch {
            _uiState.update { it.copy(isSending = true, inputText = "") }
            messageRepository.sendMessage(recipientId = recipientId, body = text)
            _uiState.update { it.copy(isSending = false) }
        }
    }
}
