package com.seven.ikar.kotlin.feature.join

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.seven.ikar.kotlin.app.AppContainer
import com.seven.ikar.kotlin.core.model.JoinChatResultStatus
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

data class JoinInviteUiState(
    val isLoading: Boolean = false,
    val message: String? = null,
    val errorMessage: String? = null,
    val pendingChatId: String? = null,
    val isPendingApproval: Boolean = false
)

class JoinInviteViewModel(
    private val container: AppContainer,
    private val inviteToken: String
) : ViewModel() {
    private val _uiState = MutableStateFlow(JoinInviteUiState(isLoading = true))
    val uiState: StateFlow<JoinInviteUiState> = _uiState.asStateFlow()

    init {
        join()
    }

    fun join() {
        if (inviteToken.isBlank()) {
            _uiState.value = JoinInviteUiState(errorMessage = "Ссылка недействительна.")
            return
        }

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null, message = null)
            runCatching {
                container.executeAuthorized { session ->
                    container.apiClient.joinChatByInviteLink(session.accessToken, inviteToken)
                }
            }.onSuccess { result ->
                when (result.status) {
                    JoinChatResultStatus.Joined -> {
                        val chatId = result.chat?.id
                        _uiState.value = if (chatId.isNullOrBlank()) {
                            JoinInviteUiState(errorMessage = "Чат недоступен после вступления.")
                        } else {
                            JoinInviteUiState(pendingChatId = chatId)
                        }
                    }

                    JoinChatResultStatus.PendingApproval -> {
                        _uiState.value = JoinInviteUiState(
                            message = "Заявка на вступление отправлена. Дождитесь одобрения администратора.",
                            isPendingApproval = true
                        )
                    }
                }
            }.onFailure { error ->
                _uiState.value = JoinInviteUiState(
                    errorMessage = error.message ?: "Не удалось открыть пригласительную ссылку."
                )
            }
        }
    }

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