package com.anypreta.bountyboard.ui.admin

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Refresh
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
import com.anypreta.bountyboard.ui.components.BBBadge
import com.anypreta.bountyboard.ui.components.BBButton
import com.anypreta.bountyboard.ui.components.BBButtonStyle
import com.anypreta.bountyboard.ui.components.BBCard
import com.anypreta.bountyboard.ui.components.Hairline
import com.anypreta.bountyboard.ui.components.ScreenColumn
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.components.SectionLabel
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.theme.Fraunces
import com.anypreta.bountyboard.ui.theme.SplineMono
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import kotlinx.coroutines.launch

class AdminServiceStatusViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var status by mutableStateOf<JsonObject?>(null)
        private set

    init {
        load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                status = container.repo.call { adminServiceStatus() }
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }
}

private fun JsonObject.bool(key: String): Boolean? =
    get(key)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isBoolean }?.asBoolean

private fun JsonObject.str(key: String): String? =
    get(key)?.takeIf { it.isJsonPrimitive }?.asString

private fun JsonObject.num(key: String): String? =
    get(key)?.takeIf { it.isJsonPrimitive && it.asJsonPrimitive.isNumber }?.asString

@Composable
fun AdminServiceStatusScreen() {
    val container = LocalAppContainer.current
    val vm: AdminServiceStatusViewModel = viewModel(factory = containerVMFactory(container) { AdminServiceStatusViewModel(it) })
    val p = BB.colors

    ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
        val status = vm.status ?: return@ScreenState
        ScreenColumn {
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                Text("Service status", style = MaterialTheme.typography.headlineMedium, color = p.text)
                BBButton("Refresh", onClick = { vm.load() }, style = BBButtonStyle.Default, small = true, leadingIcon = Icons.Outlined.Refresh)
            }

            // Known services
            val handledKeys = mutableSetOf<String>()
            listOf("atomizer", "workPerformer", "work_performer").forEach { key ->
                val el = status.get(key)
                if (el != null && el.isJsonObject) {
                    handledKeys += key
                    ServiceCard(name = key, obj = el.asJsonObject)
                }
            }

            // Workers
            listOf("syncWorkers", "workers").forEach { key ->
                val el = status.get(key)
                if (el != null && el.isJsonArray) {
                    handledKeys += key
                    BBCard(modifier = Modifier.fillMaxWidth()) {
                        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                            SectionLabel(key)
                            el.asJsonArray.forEachIndexed { i, w ->
                                if (i > 0) Hairline()
                                if (w.isJsonObject) {
                                    val wo = w.asJsonObject
                                    val healthy = wo.bool("healthy")
                                    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                                        if (healthy != null) StatusDot(if (healthy) p.ok else p.err)
                                        Text(
                                            wo.str("id") ?: wo.str("name") ?: "worker ${i + 1}",
                                            style = MaterialTheme.typography.bodyMedium,
                                            color = p.text,
                                        )
                                        wo.str("state")?.let { Text(it, fontFamily = SplineMono, style = MaterialTheme.typography.labelSmall, color = p.muted) }
                                    }
                                } else {
                                    Text(w.toString(), fontFamily = SplineMono, style = MaterialTheme.typography.bodySmall, color = p.muted)
                                }
                            }
                        }
                    }
                }
            }

            // Queues
            listOf("queues", "jobQueue", "queueDepth").forEach { key ->
                val el = status.get(key)
                if (el != null) {
                    handledKeys += key
                    BBCard(modifier = Modifier.fillMaxWidth()) {
                        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                            SectionLabel(key)
                            when {
                                el.isJsonObject -> el.asJsonObject.entrySet().forEach { (k, v) ->
                                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                                        Text(k, style = MaterialTheme.typography.bodyMedium, color = p.muted)
                                        Text(v.toString(), fontFamily = SplineMono, style = MaterialTheme.typography.bodyMedium, color = p.text)
                                    }
                                }
                                el.isJsonPrimitive -> Text("Depth: ${el.asString}", fontFamily = SplineMono, style = MaterialTheme.typography.bodyMedium, color = p.text)
                                else -> Text(el.toString(), fontFamily = SplineMono, style = MaterialTheme.typography.bodySmall, color = p.muted)
                            }
                        }
                    }
                }
            }

            // Raw — anything not yet handled
            val rest = status.entrySet().filter { it.key !in handledKeys }
            if (rest.isNotEmpty()) {
                BBCard(modifier = Modifier.fillMaxWidth()) {
                    Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        SectionLabel("Raw")
                        rest.forEachIndexed { i, (k, v) ->
                            if (i > 0) Hairline()
                            Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
                                Text(k, style = MaterialTheme.typography.titleSmall, color = p.text)
                                Text(rawValue(v), fontFamily = SplineMono, style = MaterialTheme.typography.bodySmall, color = p.muted)
                            }
                        }
                    }
                }
            }
        }
    }
}

private fun rawValue(el: JsonElement): String = when {
    el.isJsonPrimitive -> el.asString
    else -> el.toString()
}

@Composable
private fun ServiceCard(name: String, obj: JsonObject) {
    val p = BB.colors
    val healthy = obj.bool("healthy")
    BBCard(modifier = Modifier.fillMaxWidth(), topStrip = true) {
        Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                StatusDot(if (healthy == true) p.ok else p.err)
                Text(name, fontFamily = Fraunces, style = MaterialTheme.typography.titleLarge, color = p.text)
                healthy?.let { BBBadge(if (it) "Healthy" else "Down", color = if (it) p.ok else p.err) }
            }
            obj.str("breaker")?.let {
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                    Text("Breaker", style = MaterialTheme.typography.bodyMedium, color = p.muted)
                    Text(it, fontFamily = SplineMono, style = MaterialTheme.typography.bodyMedium, color = p.text)
                }
            }
            obj.num("latencyMs")?.let {
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                    Text("Latency", style = MaterialTheme.typography.bodyMedium, color = p.muted)
                    Text("${it}ms", fontFamily = SplineMono, style = MaterialTheme.typography.bodyMedium, color = p.text)
                }
            }
            obj.str("error")?.takeIf { it.isNotBlank() }?.let {
                Text(it, style = MaterialTheme.typography.bodySmall, color = p.err)
            }
        }
    }
}

@Composable
private fun StatusDot(color: Color) {
    Box(Modifier.size(10.dp).clip(CircleShape).background(color))
}
