package com.jishisongfu.duobibi.ui.mine

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.jishisongfu.duobibi.ui.theme.DbbColors

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DiagnosticsScreen(onBack: () -> Unit, vm: DiagnosticsViewModel = hiltViewModel()) {
    val items by vm.items.collectAsStateWithLifecycle()
    val running by vm.running.collectAsStateWithLifecycle()

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("运行自检", fontWeight = FontWeight.Bold, color = DbbColors.Ink) },
                navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "返回", tint = DbbColors.Ink) } },
                colors = TopAppBarDefaults.topAppBarColors(containerColor = DbbColors.Card),
            )
        },
    ) { padding ->
        Column(Modifier.padding(padding).fillMaxSize().background(MaterialTheme.colorScheme.background).padding(16.dp)) {
            Text("检查权限、浮窗、网络与后端识别是否正常。自检会真实调用一次比价识别。",
                color = DbbColors.InkSec, fontSize = 13.sp)
            Spacer(Modifier.height(12.dp))
            Button(
                onClick = vm::runAll, enabled = !running,
                modifier = Modifier.fillMaxWidth().height(46.dp), shape = RoundedCornerShape(12.dp),
                colors = ButtonDefaults.buttonColors(containerColor = DbbColors.Teal),
            ) { Text(if (items.any { it.status != DiagStatus.PENDING }) "重新自检" else "开始自检", fontWeight = FontWeight.SemiBold) }
            Spacer(Modifier.height(12.dp))
            items.forEach { DiagRow(it) }
        }
    }
}

@Composable
private fun DiagRow(item: DiagItem) {
    Row(
        Modifier.fillMaxWidth().padding(vertical = 10.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        when (item.status) {
            DiagStatus.RUNNING -> CircularProgressIndicator(Modifier.size(18.dp), color = DbbColors.Teal, strokeWidth = 2.dp)
            else -> Box(Modifier.size(12.dp).clip(CircleShape).background(dotColor(item.status)))
        }
        Spacer(Modifier.size(12.dp))
        Column(Modifier.weight(1f)) {
            Text(item.label, fontWeight = FontWeight.Medium, color = DbbColors.Ink)
            item.detail?.let { Text(it, color = DbbColors.InkTer, fontSize = 11.sp) }
        }
        Text(statusText(item.status) + (item.latencyMs?.let { " · ${it}ms" } ?: ""),
            color = dotColor(item.status), fontSize = 12.sp, fontWeight = FontWeight.SemiBold)
    }
}

private fun dotColor(s: DiagStatus): Color = when (s) {
    DiagStatus.OK -> DbbColors.Save
    DiagStatus.FAIL -> DbbColors.Up
    DiagStatus.UNKNOWN -> DbbColors.Gold
    DiagStatus.RUNNING -> DbbColors.Teal
    DiagStatus.PENDING -> DbbColors.InkTer
}

private fun statusText(s: DiagStatus): String = when (s) {
    DiagStatus.OK -> "正常"
    DiagStatus.FAIL -> "异常"
    DiagStatus.UNKNOWN -> "未知"
    DiagStatus.RUNNING -> "检测中"
    DiagStatus.PENDING -> "待检测"
}
