package app.closer.ui.answers

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.domain.model.LocalAnswer
import app.closer.domain.repository.AuthRepository
import app.closer.domain.repository.CoupleRepository
import app.closer.domain.repository.LocalAnswerRepository
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.update
import kotlinx.coroutines.launch

data class AnswerHistoryUiState(
    val answers: List<LocalAnswer> = emptyList(),
    val isPaired: Boolean = false,
    val isPairingLoaded: Boolean = false
)

@HiltViewModel
class AnswerHistoryViewModel @Inject constructor(
    private val localAnswerRepository: LocalAnswerRepository,
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository
) : ViewModel() {

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

    init {
        loadPairingState()
        viewModelScope.launch {
            localAnswerRepository.observeAnswers().collect { answers ->
                _uiState.update { it.copy(answers = answers.sortedByDescending { answer -> answer.updatedAt }) }
            }
        }
    }

    private fun loadPairingState() {
        viewModelScope.launch {
            val userId = authRepository.currentUserId
            val isPaired = userId?.let {
                runCatching { coupleRepository.getCoupleForUser(it) }.getOrNull() != null
            } ?: false
            _uiState.update { it.copy(isPaired = isPaired, isPairingLoaded = true) }
        }
    }

    fun deleteAnswer(questionId: String) {
        viewModelScope.launch {
            localAnswerRepository.deleteAnswer(questionId)
        }
    }
}
