package com.seven.ikar.kotlin.feature.contacts

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.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

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

class ContactsViewModel(private val container: AppContainer) : ViewModel() {
    private val _uiState = MutableStateFlow(ContactsUiState())
    val uiState: StateFlow<ContactsUiState> = _uiState.asStateFlow()

    fun updateQuery(value: String) {
        _uiState.value = _uiState.value.copy(query = value)
    }

    fun refresh() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            runCatching { container.resolvedContactsRepository.loadResolvedContacts() }
                .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 startDirectChat(user: DiscoverUserItem) {
        viewModelScope.launch {
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.createDirectChat(session.accessToken, user.id)
                }
            }.onSuccess { chat ->
                _uiState.value = _uiState.value.copy(pendingChatId = chat.id)
            }.onFailure { error ->
                _uiState.value = _uiState.value.copy(errorMessage = error.message)
            }
        }
    }

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

    fun filteredItems(): List<DiscoverUserItem> {
        val query = _uiState.value.query.trim()
        if (query.isBlank()) {
            return _uiState.value.items
        }

        return _uiState.value.items.filter {
            it.displayName.contains(query, ignoreCase = true) ||
                it.secondaryLine.contains(query, ignoreCase = true) ||
                it.normalizedPhoneNumber.contains(query, ignoreCase = true)
        }
    }
}
