package app.voltplan.cable.ui.system

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.voltplan.cable.CableApplication
import app.voltplan.cable.analytics.Analytics
import app.voltplan.cable.calc.SystemMetrics
import app.voltplan.cable.data.model.ElectricalSystem
import app.voltplan.cable.data.model.SavedBattery
import app.voltplan.cable.data.model.SavedCharger
import app.voltplan.cable.data.model.SavedLoad
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

data class DetailState(
    val system: ElectricalSystem? = null,
    val loads: List<SavedLoad> = emptyList(),
    val batteries: List<SavedBattery> = emptyList(),
    val chargers: List<SavedCharger> = emptyList(),
) {
    val metrics: SystemMetrics get() = SystemMetrics(loads, batteries, chargers)
}

class SystemDetailViewModel(
    app: CableApplication,
    val systemId: String,
) : ViewModel() {
    private val repo = app.repository

    val state: StateFlow<DetailState> = combine(
        repo.observeSystem(systemId),
        repo.observeLoads(systemId),
        repo.observeBatteries(systemId),
        repo.observeChargers(systemId),
    ) { system, loads, batteries, chargers ->
        DetailState(system, loads, batteries, chargers)
    }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), DetailState())

    fun logTabChange(tab: String) {
        Analytics.log("Tab Changed", mapOf("tab" to tab, "system" to (state.value.system?.name ?: "")))
    }

    fun saveSystem(name: String, location: String, iconName: String, colorName: String) {
        val current = state.value.system ?: return
        viewModelScope.launch {
            repo.upsertSystem(current.copy(name = name, location = location, iconName = iconName, colorName = colorName))
            Analytics.log("System Updated", mapOf("name" to name))
        }
    }

    fun deleteLoad(load: SavedLoad) {
        viewModelScope.launch {
            Analytics.log("Load Deleted", mapOf("name" to load.name, "system" to (state.value.system?.name ?: "")))
            repo.deleteLoad(load)
        }
    }

    fun deleteBattery(battery: SavedBattery) {
        viewModelScope.launch {
            Analytics.log("Battery Deleted", mapOf("name" to battery.name, "system" to (state.value.system?.name ?: "")))
            repo.deleteBattery(battery)
        }
    }

    fun deleteCharger(charger: SavedCharger) {
        viewModelScope.launch {
            Analytics.log("Charger Deleted", mapOf("name" to charger.name, "system" to (state.value.system?.name ?: "")))
            repo.deleteCharger(charger)
        }
    }

    fun setRuntimeGoal(hours: Double?) {
        val current = state.value.system ?: return
        viewModelScope.launch { repo.upsertSystem(current.copy(targetRuntimeHours = hours)) }
    }

    fun setChargeGoal(hours: Double?) {
        val current = state.value.system ?: return
        viewModelScope.launch { repo.upsertSystem(current.copy(targetChargeTimeHours = hours)) }
    }

    fun logBomOpened() {
        Analytics.log("Bill Of Materials Opened", mapOf("system" to (state.value.system?.name ?: "")))
    }
}
