package app.closer.ui.questions

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.model.Question
import app.closer.domain.model.QuestionCategory
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
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.launch

data class QuestionCategoryUiState(
    val isLoading: Boolean = true,
    val error: String? = null,
    val category: QuestionCategory? = null,
    val questions: List<Question> = emptyList(),
    val coupleId: String? = null
)

@HiltViewModel
class QuestionCategoryViewModel @Inject constructor(
    private val repository: QuestionRepository,
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository,
    savedStateHandle: SavedStateHandle
) : ViewModel() {

    private val categoryId: String = savedStateHandle["categoryId"] ?: ""

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

    init {
        loadCategory()
    }

    fun loadCategory() {
        viewModelScope.launch {
            _uiState.value = QuestionCategoryUiState(isLoading = true)
            try {
                val category = repository.getCategoryById(categoryId)
                val questions = repository.getQuestionsByCategory(categoryId)
                val coupleId = authRepository.currentUserId?.let { uid ->
                    runCatching { coupleRepository.getCoupleForUser(uid)?.id }.getOrNull()
                }
                _uiState.value = QuestionCategoryUiState(
                    isLoading = false,
                    category = category,
                    questions = questions,
                    coupleId = coupleId
                )
            } catch (e: Exception) {
                _uiState.value = QuestionCategoryUiState(
                    isLoading = false,
                    error = e.message ?: "Could not load this question category."
                )
            }
        }
    }
}
