package com.seven.ikar.kotlin.feature.forward

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.contacts.DiscoverUserItem
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class ForwardUiState(
    val sourceChatId: String,
    val sourceMessageId: String,
    val query: String = "",
    val items: List<DiscoverUserItem> = emptyList(),
    val isLoading: Boolean = false,
    val errorMessage: String? = null,
    val pendingChatId: String? = null
)

class ForwardViewModel(
    private val container: AppContainer,
    private val sourceChatId: String,
    private val sourceMessageId: String
) : ViewModel() {
    private val _uiState = MutableStateFlow(
        ForwardUiState(
            sourceChatId = sourceChatId,
            sourceMessageId = sourceMessageId
        )
    )
    val uiState: StateFlow<ForwardUiState> = _uiState.asStateFlow()

    private var searchJob: Job? = null

    init {
        refresh()
    }

    fun updateQuery(value: String) {
        _uiState.value = _uiState.value.copy(query = value)
        searchJob?.cancel()
        searchJob = viewModelScope.launch {
            delay(250)
            refresh()
        }
    }

    fun refresh() {
        viewModelScope.launch {
            val query = _uiState.value.query
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            runCatching { container.resolvedContactsRepository.loadMergedCandidates(query) }
                .onSuccess { items ->
                    _uiState.value = _uiState.value.copy(items = items, isLoading = false, errorMessage = null)
                }
                .onFailure { error ->
                    _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = error.message)
                }
        }
    }

    fun forwardToUser(user: DiscoverUserItem) {
        viewModelScope.launch {
            runCatching {
                container.executeAuthorized { session ->
                    val chat = container.apiClient.createDirectChat(session.accessToken, user.id)
                    container.apiClient.forwardMessage(
                        accessToken = session.accessToken,
                        sourceChatId = sourceChatId,
                        messageId = sourceMessageId,
                        targetChatId = chat.id
                    )
                    chat.id
                }
            }.onSuccess { chatId ->
                _uiState.value = _uiState.value.copy(pendingChatId = chatId)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(errorMessage = error.message)
            }
        }
    }

    fun consumePendingChatNavigation() {
        _uiState.value = _uiState.value.copy(pendingChatId = null)
    }
}
