package app.closer.ui.pairing

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.navigation.AppRoute
import app.closer.domain.repository.InviteRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class AcceptInviteUiState(
    val code: String = "",
    val isLoading: Boolean = false,
    val error: String? = null,
    val navigateTo: String? = null
)

@HiltViewModel
class AcceptInviteViewModel @Inject constructor(
    private val inviteRepository: InviteRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(AcceptInviteUiState())
    val uiState: StateFlow<AcceptInviteUiState> = _uiState.asStateFlow()

    fun updateCode(raw: String) {
        val filtered = raw.uppercase().filter { it in CODE_CHARS }.take(6)
        _uiState.update { it.copy(code = filtered, error = null) }
    }

    fun lookupCode() {
        val code = _uiState.value.code
        if (code.length < 6) {
            _uiState.update { it.copy(error = "Please enter all 6 characters.") }
            return
        }
        _uiState.update { it.copy(isLoading = true, error = null) }
        viewModelScope.launch {
            // The invite is no longer readable client-side. Move directly to the
            // confirmation screen; the Cloud Function will validate the code and
            // perform the acceptance atomically when the user confirms.
            _uiState.update { it.copy(isLoading = false, navigateTo = AppRoute.inviteConfirm(code)) }
        }
    }

    fun onNavigated() = _uiState.update { it.copy(navigateTo = null) }
    fun dismissError() = _uiState.update { it.copy(error = null) }

    companion object {
        private const val CODE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
    }
}
