package app.closer.ui.settings

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.navigation.AppRoute
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import app.closer.domain.repository.SettingsRepository
import app.closer.domain.repository.ThemeMode
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 SettingsUiState(
    val isLoading: Boolean = true,
    val displayName: String = "",
    val email: String = "",
    val partnerName: String? = null,
    val isPaired: Boolean = false,
    val isSigningOut: Boolean = false,
    val themeMode: ThemeMode = ThemeMode.DEVICE,
    val navigateTo: String? = null
)

@HiltViewModel
class SettingsViewModel @Inject constructor(
    private val authRepository: AuthRepository,
    private val userRepository: UserRepository,
    private val coupleRepository: CoupleRepository,
    private val settingsRepository: SettingsRepository
) : ViewModel() {

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

    init {
        loadSettings()
        observeThemeMode()
    }

    private fun observeThemeMode() {
        viewModelScope.launch {
            settingsRepository.settings.collect { settings ->
                _uiState.update { it.copy(themeMode = settings.themeMode) }
            }
        }
    }

    fun setThemeMode(mode: ThemeMode) {
        _uiState.update { it.copy(themeMode = mode) }
        viewModelScope.launch { settingsRepository.setThemeMode(mode) }
    }

    private fun loadSettings() {
        viewModelScope.launch {
            val userId = authRepository.currentUserId ?: run {
                _uiState.update { it.copy(isLoading = false) }
                return@launch
            }
            val email = authRepository.currentUserEmail ?: ""
            val user = runCatching { userRepository.getUser(userId) }
                .onFailure { Log.w(TAG, "Could not load current user profile", it) }
                .getOrNull()
            val couple = coupleRepository.getCoupleForUser(userId)
            val partnerId = couple?.userIds?.firstOrNull { it != userId }
            val partnerName = partnerId?.let {
                runCatching { userRepository.getUser(it)?.displayName }
                    .onFailure { e -> Log.w(TAG, "Could not load partner display name", e) }
                    .getOrNull()
            }
            _uiState.update {
                it.copy(
                    isLoading = false,
                    displayName = user?.displayName ?: "",
                    email = email,
                    partnerName = partnerName,
                    isPaired = couple != null
                )
            }
        }
    }

    fun signOut() {
        _uiState.update { it.copy(isSigningOut = true) }
        viewModelScope.launch {
            authRepository.signOut()
            _uiState.update { it.copy(isSigningOut = false, navigateTo = AppRoute.ONBOARDING) }
        }
    }

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

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