package com.durian.tssparty.presentation.screens

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.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.durian.tssparty.BuildConfig
import com.durian.tssparty.domain.model.AppSettings
import com.durian.tssparty.domain.model.NetworkType

/**
 * Connection test result
 */
data class ConnectionTestResult(
    val success: Boolean,
    val message: String,
    val latency: Long? = null
)

/**
 * Settings screen matching service-party-app/src/pages/Settings.tsx
 * Full implementation with test connection buttons and Account Service URL
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    settings: AppSettings,
    isConnected: Boolean,
    messageRouterStatus: ConnectionTestResult? = null,
    accountServiceStatus: ConnectionTestResult? = null,
    kavaApiStatus: ConnectionTestResult? = null,
    onSaveSettings: (AppSettings) -> Unit,
    onTestMessageRouter: (String) -> Unit = {},
    onTestAccountService: (String) -> Unit = {},
    onTestKavaApi: (String) -> Unit = {}
) {
    var messageRouterUrl by remember { mutableStateOf(settings.messageRouterUrl) }
    var accountServiceUrl by remember { mutableStateOf(settings.accountServiceUrl) }
    var kavaRpcUrl by remember { mutableStateOf(settings.kavaRpcUrl) }
    var networkType by remember { mutableStateOf(settings.networkType) }
    var hasChanges by remember { mutableStateOf(false) }

    // Test connection states
    var isTestingMessageRouter by remember { mutableStateOf(false) }
    var isTestingAccountService by remember { mutableStateOf(false) }
    var isTestingKavaApi by remember { mutableStateOf(false) }

    // Local test results (for display)
    var localMessageRouterResult by remember { mutableStateOf<ConnectionTestResult?>(null) }
    var localAccountServiceResult by remember { mutableStateOf<ConnectionTestResult?>(null) }
    var localKavaApiResult by remember { mutableStateOf<ConnectionTestResult?>(null) }

    // Update local results when props change
    LaunchedEffect(messageRouterStatus) {
        if (messageRouterStatus != null) {
            localMessageRouterResult = messageRouterStatus
            isTestingMessageRouter = false
        }
    }
    LaunchedEffect(accountServiceStatus) {
        if (accountServiceStatus != null) {
            localAccountServiceResult = accountServiceStatus
            isTestingAccountService = false
        }
    }
    LaunchedEffect(kavaApiStatus) {
        if (kavaApiStatus != null) {
            localKavaApiResult = kavaApiStatus
            isTestingKavaApi = false
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        // Header
        Text(
            text = "设置",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "配置应用程序连接和网络设置",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(24.dp))

        // Connection status overview
        Card(
            colors = CardDefaults.cardColors(
                containerColor = if (isConnected)
                    MaterialTheme.colorScheme.primaryContainer
                else
                    MaterialTheme.colorScheme.errorContainer
            ),
            modifier = Modifier.fillMaxWidth()
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    if (isConnected) Icons.Default.CheckCircle else Icons.Default.Warning,
                    contentDescription = null,
                    tint = if (isConnected)
                        MaterialTheme.colorScheme.onPrimaryContainer
                    else
                        MaterialTheme.colorScheme.onErrorContainer
                )
                Spacer(modifier = Modifier.width(12.dp))
                Column {
                    Text(
                        text = if (isConnected) "应用就绪" else "连接异常",
                        fontWeight = FontWeight.Medium,
                        color = if (isConnected)
                            MaterialTheme.colorScheme.onPrimaryContainer
                        else
                            MaterialTheme.colorScheme.onErrorContainer
                    )
                    Text(
                        text = if (isConnected) "所有服务正常运行" else "请检查网络设置",
                        style = MaterialTheme.typography.bodySmall,
                        color = if (isConnected)
                            MaterialTheme.colorScheme.onPrimaryContainer.copy(alpha = 0.7f)
                        else
                            MaterialTheme.colorScheme.onErrorContainer.copy(alpha = 0.7f)
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        // Section: Connection Settings
        Text(
            text = "连接设置",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold
        )

        Spacer(modifier = Modifier.height(16.dp))

        // Message Router URL
        Card(modifier = Modifier.fillMaxWidth()) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "消息路由服务",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "TSS 多方计算消息中继服务器",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(12.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedTextField(
                        value = messageRouterUrl,
                        onValueChange = {
                            messageRouterUrl = it
                            hasChanges = true
                            localMessageRouterResult = null
                        },
                        label = { Text("服务地址") },
                        placeholder = { Text("mpc-grpc.szaiai.com:443") },
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        leadingIcon = {
                            Icon(Icons.Default.Cloud, contentDescription = null)
                        }
                    )
                    Button(
                        onClick = {
                            isTestingMessageRouter = true
                            localMessageRouterResult = null
                            onTestMessageRouter(messageRouterUrl)
                        },
                        enabled = !isTestingMessageRouter && messageRouterUrl.isNotBlank()
                    ) {
                        if (isTestingMessageRouter) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text("测试")
                        }
                    }
                }

                // Test result
                localMessageRouterResult?.let { result ->
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            if (result.success) Icons.Default.CheckCircle else Icons.Default.Error,
                            contentDescription = null,
                            tint = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = result.message + (result.latency?.let { " (${it}ms)" } ?: ""),
                            style = MaterialTheme.typography.bodySmall,
                            color = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Account Service URL
        Card(modifier = Modifier.fillMaxWidth()) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "账户服务",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "会话管理和账户 API 服务",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(12.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedTextField(
                        value = accountServiceUrl,
                        onValueChange = {
                            accountServiceUrl = it
                            hasChanges = true
                            localAccountServiceResult = null
                        },
                        label = { Text("API 地址") },
                        placeholder = { Text("https://rwaapi.szaiai.com") },
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        leadingIcon = {
                            Icon(Icons.Default.Api, contentDescription = null)
                        }
                    )
                    Button(
                        onClick = {
                            isTestingAccountService = true
                            localAccountServiceResult = null
                            onTestAccountService(accountServiceUrl)
                        },
                        enabled = !isTestingAccountService && accountServiceUrl.isNotBlank()
                    ) {
                        if (isTestingAccountService) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text("测试")
                        }
                    }
                }

                // Test result
                localAccountServiceResult?.let { result ->
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            if (result.success) Icons.Default.CheckCircle else Icons.Default.Error,
                            contentDescription = null,
                            tint = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = result.message + (result.latency?.let { " (${it}ms)" } ?: ""),
                            style = MaterialTheme.typography.bodySmall,
                            color = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        // Section: Blockchain Network
        Text(
            text = "区块链网络",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold
        )

        Spacer(modifier = Modifier.height(8.dp))

        Text(
            text = "选择要连接的 Kava 区块链网络",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        Spacer(modifier = Modifier.height(12.dp))

        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            FilterChip(
                selected = networkType == NetworkType.MAINNET,
                onClick = {
                    networkType = NetworkType.MAINNET
                    kavaRpcUrl = "https://evm.kava.io"
                    hasChanges = true
                    localKavaApiResult = null
                },
                label = { Text("主网 (Kava)") },
                leadingIcon = if (networkType == NetworkType.MAINNET) {
                    { Icon(Icons.Default.Check, contentDescription = null, Modifier.size(18.dp)) }
                } else null
            )
            FilterChip(
                selected = networkType == NetworkType.TESTNET,
                onClick = {
                    networkType = NetworkType.TESTNET
                    kavaRpcUrl = "https://evm.testnet.kava.io"
                    hasChanges = true
                    localKavaApiResult = null
                },
                label = { Text("测试网") },
                leadingIcon = if (networkType == NetworkType.TESTNET) {
                    { Icon(Icons.Default.Check, contentDescription = null, Modifier.size(18.dp)) }
                } else null
            )
        }

        Spacer(modifier = Modifier.height(16.dp))

        // Kava RPC URL
        Card(modifier = Modifier.fillMaxWidth()) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "Kava RPC 节点",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "区块链交易和查询 API",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(12.dp))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    OutlinedTextField(
                        value = kavaRpcUrl,
                        onValueChange = {
                            kavaRpcUrl = it
                            hasChanges = true
                            localKavaApiResult = null
                        },
                        label = { Text("RPC 地址") },
                        placeholder = { Text("https://evm.kava.io") },
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        leadingIcon = {
                            Icon(Icons.Default.Link, contentDescription = null)
                        }
                    )
                    Button(
                        onClick = {
                            isTestingKavaApi = true
                            localKavaApiResult = null
                            onTestKavaApi(kavaRpcUrl)
                        },
                        enabled = !isTestingKavaApi && kavaRpcUrl.isNotBlank()
                    ) {
                        if (isTestingKavaApi) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(16.dp),
                                strokeWidth = 2.dp,
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text("测试")
                        }
                    }
                }

                // Test result
                localKavaApiResult?.let { result ->
                    Spacer(modifier = Modifier.height(8.dp))
                    Row(verticalAlignment = Alignment.CenterVertically) {
                        Icon(
                            if (result.success) Icons.Default.CheckCircle else Icons.Default.Error,
                            contentDescription = null,
                            tint = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error,
                            modifier = Modifier.size(16.dp)
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = result.message + (result.latency?.let { " (${it}ms)" } ?: ""),
                            style = MaterialTheme.typography.bodySmall,
                            color = if (result.success)
                                MaterialTheme.colorScheme.primary
                            else
                                MaterialTheme.colorScheme.error
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(24.dp))

        // Section: About
        Text(
            text = "关于",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold
        )

        Spacer(modifier = Modifier.height(12.dp))

        Card(
            modifier = Modifier.fillMaxWidth()
        ) {
            Column(
                modifier = Modifier.padding(16.dp)
            ) {
                AboutRow("应用名称", "TSS Party")
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("版本", BuildConfig.VERSION_NAME)
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("版本号", BuildConfig.VERSION_CODE.toString())
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("构建类型", if (BuildConfig.DEBUG) "Debug" else "Release")
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("TSS 协议", "GG20")
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("区块链", "Kava EVM")
                Divider(modifier = Modifier.padding(vertical = 8.dp))
                AboutRow("项目", "RWADurian MPC System")
            }
        }

        Spacer(modifier = Modifier.height(24.dp))
        Spacer(modifier = Modifier.weight(1f))

        // Save button
        Button(
            onClick = {
                onSaveSettings(
                    AppSettings(
                        messageRouterUrl = messageRouterUrl,
                        accountServiceUrl = accountServiceUrl,
                        kavaRpcUrl = kavaRpcUrl,
                        networkType = networkType
                    )
                )
                hasChanges = false
            },
            modifier = Modifier
                .fillMaxWidth()
                .height(56.dp),
            enabled = hasChanges
        ) {
            Icon(Icons.Default.Save, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("保存设置")
        }
    }
}

@Composable
private fun AboutRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Text(
            text = value,
            style = MaterialTheme.typography.bodyMedium,
            fontWeight = FontWeight.Medium
        )
    }
}
