package app.closer.ui.wheel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.EntitlementChecker
import app.closer.domain.model.QuestionSession
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import app.closer.domain.repository.QuestionSessionRepository
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.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

data class WheelHistoryUiState(
    val isLoading: Boolean = false,
    val sessions: List<QuestionSession> = emptyList(),
    val hasPremium: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class WheelHistoryViewModel @Inject constructor(
    private val sessionRepository: QuestionSessionRepository,
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository,
    entitlementChecker: EntitlementChecker
) : ViewModel() {

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

    init {
        entitlementChecker.isPremium()
            .onEach { premium ->
                _uiState.update { it.copy(hasPremium = premium) }
                if (premium) load()
            }
            .launchIn(viewModelScope)
    }

    fun load() {
        val uid = authRepository.currentUserId ?: return
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, error = null) }
            val couple = coupleRepository.getCoupleForUser(uid)
            if (couple == null) {
                _uiState.update { it.copy(isLoading = false) }
                return@launch
            }
            sessionRepository.getSessionsForCouple(couple.id)
                .onSuccess { sessions ->
                    _uiState.update { it.copy(isLoading = false, sessions = sessions) }
                }
                .onFailure { e ->
                    _uiState.update { it.copy(isLoading = false, error = e.message ?: "Couldn't load your past games.") }
                }
        }
    }
}
