package com.example.ops_android.ui.settings

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.ops_android.ui.LocalAppContainer
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PrinterTestScreen(onBack: () -> Unit) {
    val appContainer = LocalAppContainer.current
    val printerManager = appContainer.printerManager
    val sessionManager = appContainer.sessionManager
    val scope = rememberCoroutineScope()

    var isTesting by remember { mutableStateOf(false) }
    var testResult by remember { mutableStateOf<String?>(null) }
    var testSuccess by remember { mutableStateOf<Boolean?>(null) }

    val isConnected = remember { derivedStateOf { printerManager?.isConnected() == true } }
    val firmware = remember { derivedStateOf { printerManager?.getFirmwareVersion() } }
    val unwindMm = remember { derivedStateOf { sessionManager.cachedUnwindMm } }
    val blackMarkEnabled = remember { derivedStateOf { sessionManager.cachedBlackMarkEnabled } }

    fun runTest(label: String, action: suspend () -> Unit) {
        val pm = printerManager ?: return
        isTesting = true
        testResult = null
        testSuccess = null
        scope.launch {
            withContext(Dispatchers.IO) {
                try {
                    action()
                    testSuccess = true
                    testResult = "[$label] 执行完成"
                } catch (e: Exception) {
                    testSuccess = false
                    testResult = "[$label] 失败: ${e.message}"
                } finally {
                    isTesting = false
                }
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("打印机测试") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF667EEA),
                    titleContentColor = Color.White,
                    navigationIconContentColor = Color.White
                )
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .padding(16.dp)
                .verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            Card {
                Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("连接状态", color = Color.Gray)
                        Text(
                            if (isConnected.value) "已连接" else "未连接",
                            color = if (isConnected.value) Color(0xFF4CAF50) else Color(0xFFF44336)
                        )
                    }
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("固件版本", color = Color.Gray)
                        Text(firmware.value ?: "未知")
                    }
                }
            }

            Card {
                Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("黑标检测", color = Color.Gray)
                        Text(if (blackMarkEnabled.value) "启用" else "禁用")
                    }
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                        Text("走纸长度", color = Color.Gray)
                        Text("${unwindMm.value} mm")
                    }
                }
            }

            HorizontalDivider()

            Text("走纸测试", style = MaterialTheme.typography.titleMedium)

            Button(
                onClick = {
                    runTest("空走纸") {
                        val pm = printerManager!!
                        pm.initDevice().getOrThrow()
                        pm.commit().getOrThrow()
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = isConnected.value && !isTesting
            ) {
                Text("测试A：空走纸（无内容，看默认基线）")
            }

            Button(
                onClick = {
                    runTest("空走纸 + 5行换行") {
                        val pm = printerManager!!
                        pm.initDevice().getOrThrow()
                        pm.addLineFeed(5)
                        pm.commit().getOrThrow()
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = isConnected.value && !isTesting,
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF5C6BC0))
            ) {
                Text("测试B：空走纸 + 5行换行")
            }

            Button(
                onClick = {
                    runTest("空走纸 + 10行换行") {
                        val pm = printerManager!!
                        pm.initDevice().getOrThrow()
                        pm.addLineFeed(10)
                        pm.commit().getOrThrow()
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = isConnected.value && !isTesting,
                colors = ButtonDefaults.buttonColors(containerColor = Color(0xFF8D6E63))
            ) {
                Text("测试C：空走纸 + 10行换行")
            }

            Text(
                "目标：对比B(5行)和C(10行)的出纸长度，算出每行=多少mm，填入代码中校准",
                fontSize = 13.sp,
                color = Color.Gray
            )

            HorizontalDivider()

            Text("SDK调试", style = MaterialTheme.typography.titleMedium)

            Button(
                onClick = {
                    val pm = printerManager
                    if (pm != null) {
                        val unwindVal = pm.getUnwindPaperLenInt()
                        val feedSpaceVal = pm.getFeedPaperSpaceInt()
                        testSuccess = null
                        testResult = "getUnwindPaperLen = $unwindVal, getFeedPaperSpace = $feedSpaceVal"
                    }
                },
                modifier = Modifier.fillMaxWidth(),
                enabled = isConnected.value && !isTesting
            ) {
                Text("读取 SDK 内部走纸参数")
            }

            if (!isConnected.value && printerManager != null) {
                Button(
                    onClick = { printerManager?.bindService() },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.secondary)
                ) {
                    Text("绑定打印服务")
                }
            }

            testResult?.let {
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = if (testSuccess == true) Color(0xFFE8F5E9) else if (testSuccess == false) Color(0xFFFFEBEE) else Color(0xFFF5F5F5)
                    )
                ) {
                    Text(
                        text = it,
                        modifier = Modifier.padding(12.dp),
                        color = when (testSuccess) {
                            true -> Color(0xFF2E7D32)
                            false -> Color(0xFFC62828)
                            else -> Color.Gray
                        },
                        fontSize = 14.sp
                    )
                }
            }
        }
    }
}
