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 androidx.lifecycle.viewmodel.compose.viewModel
import com.example.ops_android.BuildConfig
import com.example.ops_android.ui.LocalAppContainer

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onBack: () -> Unit,
    onPrinterTest: () -> Unit = {},
    viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory(LocalAppContainer.current.sessionManager))
) {
    val uiState by viewModel.uiState.collectAsState()

    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(16.dp)
        ) {
            Text(
                text = "服务器配置",
                style = MaterialTheme.typography.titleMedium
            )

            OutlinedTextField(
                value = uiState.apiBaseUrl,
                onValueChange = viewModel::onUrlChange,
                label = { Text("API 地址") },
                placeholder = { Text("例如: http://192.168.1.100:8080/api") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                Button(
                    onClick = { viewModel.saveUrl() },
                    modifier = Modifier.weight(1f)
                ) {
                    Text("保存")
                }

                Button(
                    onClick = { viewModel.testConnection() },
                    modifier = Modifier.weight(1f),
                    enabled = !uiState.isTesting,
                    colors = ButtonDefaults.buttonColors(
                        containerColor = if (uiState.testSuccess) Color(0xFF4CAF50)
                        else if (uiState.testResult != null && !uiState.testSuccess) Color(0xFFF44336)
                        else MaterialTheme.colorScheme.secondary
                    )
                ) {
                    if (uiState.isTesting) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            color = Color.White,
                            strokeWidth = 2.dp
                        )
                    } else {
                        Text("测试连接")
                    }
                }
            }

            uiState.message?.let {
                Text(
                    text = it,
                    color = MaterialTheme.colorScheme.primary,
                    fontSize = 14.sp
                )
            }

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

            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

            Text("打印机设置", style = MaterialTheme.typography.titleMedium)

            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                Text("黑标检测")
                Switch(checked = uiState.blackMarkEnabled, onCheckedChange = viewModel::onBlackMarkChange)
            }

            if (!uiState.blackMarkEnabled) {
                OutlinedTextField(
                    value = uiState.unwindMm,
                    onValueChange = viewModel::onUnwindMmChange,
                    label = { Text("单次走纸长度 (mm)") },
                    suffix = { Text("mm") },
                    singleLine = true,
                    modifier = Modifier.fillMaxWidth()
                )
                Button(onClick = { viewModel.saveUnwindMm() }, modifier = Modifier.fillMaxWidth()) {
                    Text("保存走纸长度")
                }
                Button(onClick = onPrinterTest, modifier = Modifier.fillMaxWidth(), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.secondary)) {
                    Text("测试打印机")
                }
            }

            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

            Text("标签尺寸", style = MaterialTheme.typography.titleMedium)

            OutlinedTextField(
                value = uiState.labelWidthMm,
                onValueChange = viewModel::onLabelWidthChange,
                label = { Text("标签宽度 (mm)") },
                suffix = { Text("mm") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            OutlinedTextField(
                value = uiState.labelHeightMm,
                onValueChange = viewModel::onLabelHeightChange,
                label = { Text("标签高度 (mm)") },
                suffix = { Text("mm") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Button(onClick = { viewModel.saveLabelSize() }, modifier = Modifier.fillMaxWidth()) {
                Text("保存标签尺寸")
            }

            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

            Text("打印校准", style = MaterialTheme.typography.titleMedium)

            OutlinedTextField(
                value = uiState.printRetractMm,
                onValueChange = viewModel::onPrintRetractMmChange,
                label = { Text("打印前回退长度 (mm)") },
                suffix = { Text("mm") },
                singleLine = true,
                modifier = Modifier.fillMaxWidth()
            )

            Button(onClick = { viewModel.savePrintRetractMm() }, modifier = Modifier.fillMaxWidth()) {
                Text("保存回退长度")
            }

            HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp))

            Text(
                text = "关于",
                style = MaterialTheme.typography.titleMedium
            )

            Card {
                Column(modifier = Modifier.padding(16.dp)) {
                    InfoRow("应用名称", "OPS 运营管理系统")
                    InfoRow("版本", "v${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
                    InfoRow("作者", BuildConfig.AUTHOR)
                    InfoRow("构建日期", BuildConfig.BUILD_DATE)
                }
            }
        }
    }
}

@Composable
private fun InfoRow(label: String, value: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(text = label, color = Color.Gray)
        Text(text = value)
    }
}
