package app.closer.ui.wheel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.closer.core.billing.CouplePremiumChecker
import app.closer.data.challenges.ChallengesCatalog
import app.closer.data.remote.FirestoreCapsuleDataSource
import app.closer.data.remote.FirestoreChallengeDataSource
import app.closer.domain.model.QuestionSession
import app.closer.domain.model.TimeCapsule
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.async
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 CompletedChallengeEntry(
    val challengeId: String,
    val title: String,
    val emoji: String,
    val startedAt: Long
)

data class GameHistoryUiState(
    val isLoading: Boolean = false,
    val sessions: List<QuestionSession> = emptyList(),
    val completedChallenges: List<CompletedChallengeEntry> = emptyList(),
    val unlockedCapsules: List<TimeCapsule> = emptyList(),
    val hasPremium: Boolean = false,
    val error: String? = null
)

@HiltViewModel
class GameHistoryViewModel @Inject constructor(
    private val sessionRepository: QuestionSessionRepository,
    private val authRepository: AuthRepository,
    private val coupleRepository: CoupleRepository,
    private val challengeDataSource: FirestoreChallengeDataSource,
    private val capsuleDataSource: FirestoreCapsuleDataSource,
    premiumChecker: CouplePremiumChecker
) : ViewModel() {

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

    init {
        premiumChecker.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
            }
            val coupleId = couple.id

            val sessionsDeferred = async { sessionRepository.getSessionsForCouple(coupleId) }
            val challengesDeferred = async { runCatching { challengeDataSource.getCompletedChallengeIds(coupleId) }.getOrElse { emptyList() } }
            val capsulesDeferred = async { runCatching { capsuleDataSource.getCapsules(coupleId) }.getOrElse { emptyList() } }

            val sessionsResult = sessionsDeferred.await()
            val completedChallengeIds = challengesDeferred.await()
            val allCapsules = capsulesDeferred.await()

            val completedChallenges = completedChallengeIds.mapNotNull { (challengeId, startedAt) ->
                val def = ChallengesCatalog.findById(challengeId) ?: return@mapNotNull null
                CompletedChallengeEntry(
                    challengeId = challengeId,
                    title = def.title,
                    emoji = def.emoji,
                    startedAt = startedAt
                )
            }.sortedByDescending { it.startedAt }

            val unlockedCapsules = allCapsules.filter { it.status == "unlocked" }

            sessionsResult
                .onSuccess { sessions ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            sessions = sessions,
                            completedChallenges = completedChallenges,
                            unlockedCapsules = unlockedCapsules
                        )
                    }
                }
                .onFailure { e ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            completedChallenges = completedChallenges,
                            unlockedCapsules = unlockedCapsules,
                            error = e.message ?: "Couldn't load your past games."
                        )
                    }
                }
        }
    }
}
