package app.closer.ui.onboarding

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.model.AuthState
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.UserRepository
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 OnboardingUiState(
    val isCheckingAuth: Boolean = true,
    val navigateTo: String? = null
)

@HiltViewModel
class OnboardingViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository
) : ViewModel() {

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

    init {
        viewModelScope.launch {
            authRepository.authState.collect { authState ->
                when (authState) {
                    is AuthState.Loading -> _uiState.update { it.copy(isCheckingAuth = true) }
                    is AuthState.Unauthenticated -> _uiState.update { it.copy(isCheckingAuth = false, navigateTo = null) }
                    is AuthState.Authenticated -> {
                        val user = runCatching { userRepository.getUser(authState.userId) }
                            .onFailure { Log.w(TAG, "Could not load user profile during onboarding", it) }
                            .getOrNull()
                        val destination = when {
                            user == null || user.displayName.isBlank() || user.sex.isBlank() -> "create_profile"
                            else -> "home"
                        }
                        _uiState.update { it.copy(isCheckingAuth = false, navigateTo = destination) }
                    }
                }
            }
        }
    }

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

    companion object {
        private const val TAG = "OnboardingViewModel"
    }
}
