package app.voltplan.cable.ui.systems

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import app.voltplan.cable.CableApplication
import app.voltplan.cable.analytics.Analytics
import app.voltplan.cable.data.model.ElectricalSystem
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 SystemSummary(
    val system: ElectricalSystem,
    val loadCount: Int,
    val totalPower: Double,
)

class SystemsViewModel(app: Application) : AndroidViewModel(app) {
    private val repo = (app as CableApplication).repository

    val systems: StateFlow<List<SystemSummary>> =
        combine(repo.observeSystems(), repo.observeAllLoads()) { systems, loads ->
            systems.map { system ->
                val systemLoads = loads.filter { it.systemId == system.id }
                SystemSummary(
                    system = system,
                    loadCount = systemLoads.size,
                    totalPower = systemLoads.sumOf { it.power },
                )
            }
        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList())

    /** Creates a system and returns its id via the callback. [source] is for analytics. */
    fun createSystem(preferredName: String?, source: String, randomColor: Boolean, onCreated: (String) -> Unit) {
        viewModelScope.launch {
            val base = preferredName?.trim().takeUnless { it.isNullOrEmpty() } ?: "New System"
            val name = repo.uniqueSystemName(base)
            val color = if (randomColor) SystemIconMapper.colorOptions.random() else "blue"
            val system = ElectricalSystem(
                name = name,
                iconName = SystemIconMapper.iconFor(name),
                colorName = color,
            )
            repo.upsertSystem(system)
            Analytics.log("System Created", mapOf("name" to name, "source" to source))
            onCreated(system.id)
        }
    }

    fun logCreateNavigation() = Analytics.log("System Create Navigation")

    fun logOpen(summary: SystemSummary, source: String) {
        Analytics.log(
            "System Opened",
            mapOf("name" to summary.system.name, "source" to source, "loads" to summary.loadCount),
        )
    }

    fun deleteSystem(summary: SystemSummary) {
        viewModelScope.launch {
            Analytics.log(
                "System Deleted",
                mapOf("name" to summary.system.name, "loads" to summary.loadCount),
            )
            repo.deleteSystem(summary.system)
        }
    }
}

fun summaryPowerLabel(totalPower: Double): String =
    if (totalPower >= 1000) String.format("%.1fkW", totalPower / 1000) else String.format("%.0fW", totalPower)
