package app.closer.ui.questions

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.CouplePremiumChecker
import app.closer.domain.model.QuestionCategory
import app.closer.domain.repository.QuestionRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

data class QuestionPackItem(
    val category: QuestionCategory,
    val questionCount: Int,
    val isPremium: Boolean = false,
    val isLocked: Boolean = false
)

data class QuestionPackLibraryUiState(
    val isLoading: Boolean = true,
    val error: String? = null,
    val packs: List<QuestionPackItem> = emptyList()
)

@HiltViewModel
class QuestionPackLibraryViewModel @Inject constructor(
    private val repository: QuestionRepository,
    private val premiumChecker: CouplePremiumChecker
) : ViewModel() {

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

    init {
        loadPacks()
    }

    fun loadPacks() {
        viewModelScope.launch {
            _uiState.value = QuestionPackLibraryUiState(isLoading = true)
            try {
                val hasPremium = premiumChecker.isPremium().first()
                val packs = repository.getCategories().map { category ->
                    val isPremium = category.access == "premium"
                    QuestionPackItem(
                        category = category,
                        questionCount = repository.getQuestionCountByCategory(category.id),
                        isPremium = isPremium,
                        isLocked = isPremium && !hasPremium
                    )
                }
                _uiState.value = QuestionPackLibraryUiState(isLoading = false, packs = packs)
            } catch (e: Exception) {
                _uiState.value = QuestionPackLibraryUiState(
                    isLoading = false,
                    error = e.message ?: "Could not load question packs."
                )
            }
        }
    }
}
