package com.omixlab.lckcontrol.ui.dashboard

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.omixlab.lckcontrol.data.local.AppPreferences
import com.omixlab.lckcontrol.data.remote.LckApiService
import com.omixlab.lckcontrol.data.repository.ChatRepository
import com.omixlab.lckcontrol.data.repository.StreamPlanRepository
import com.omixlab.lckcontrol.shared.StreamPlan
import com.omixlab.lckcontrol.streaming.StreamingManager
import com.omixlab.lckcontrol.streaming.StreamingState
import com.omixlab.lckcontrol.streaming.StreamingStats
import com.omixlab.lckcontrol.util.GameInfoProvider
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class DashboardViewModel @Inject constructor(
    private val streamPlanRepository: StreamPlanRepository,
    private val apiService: LckApiService,
    private val appPreferences: AppPreferences,
    val gameInfoProvider: GameInfoProvider,
    private val streamingManager: StreamingManager,
    private val chatRepository: ChatRepository,
) : ViewModel() {

    val plans: StateFlow<List<StreamPlan>> = streamPlanRepository.observePlans()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val streamingState: StateFlow<StreamingState> = streamingManager.state
    val streamingStats: StateFlow<StreamingStats> = streamingManager.stats
    val streamingManagerInstance: StreamingManager = streamingManager

    val unreadCounts: StateFlow<Map<String, Int>> = chatRepository.unreadCounts

    private val _backendHealthy = MutableStateFlow<Boolean?>(null)
    val backendHealthy: StateFlow<Boolean?> = _backendHealthy.asStateFlow()

    private val _backendVersion = MutableStateFlow<String?>(null)
    val backendVersion: StateFlow<String?> = _backendVersion.asStateFlow()

    private val _defaultExecutionMode = MutableStateFlow(appPreferences.getDefaultExecutionMode())
    val defaultExecutionMode: StateFlow<String> = _defaultExecutionMode.asStateFlow()

    init {
        viewModelScope.launch {
            try { streamPlanRepository.syncPlans() } catch (_: Exception) {}
        }
        viewModelScope.launch {
            while (true) {
                try {
                    val response = apiService.healthCheck()
                    _backendHealthy.value = true
                    _backendVersion.value = response.version
                } catch (_: Exception) {
                    _backendHealthy.value = false
                }
                delay(5_000)
            }
        }
    }

    fun setDefaultExecutionMode(mode: String) {
        _defaultExecutionMode.value = mode
        appPreferences.setDefaultExecutionMode(mode)
    }

    fun clearEndedPlans() {
        viewModelScope.launch {
            val ended = plans.value.filter { it.status == "ENDED" }
            for (plan in ended) {
                try { streamPlanRepository.deletePlan(plan.planId) } catch (_: Exception) {}
            }
        }
    }
}
