package com.durian.tssparty.presentation.screens

import android.app.Activity
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
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.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import android.graphics.Bitmap
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.ui.graphics.asImageBitmap
import com.durian.tssparty.domain.model.EnergyPointsToken
import com.durian.tssparty.domain.model.FuturePointsToken
import com.durian.tssparty.domain.model.GreenPointsToken
import com.durian.tssparty.domain.model.NetworkType
import com.durian.tssparty.domain.model.SessionStatus
import com.durian.tssparty.domain.model.ShareRecord
import com.durian.tssparty.domain.model.TokenConfig
import com.durian.tssparty.domain.model.TokenType
import com.durian.tssparty.domain.model.WalletBalance
import com.durian.tssparty.util.TransactionUtils
import com.google.zxing.BarcodeFormat
import com.google.zxing.qrcode.QRCodeWriter
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions
import kotlinx.coroutines.launch
import java.math.BigInteger

/**
 * Transfer Screen - matches service-party-app Home.tsx transfer flow exactly
 *
 * Flow:
 * 1. input - Enter recipient address and amount (QR scan or manual input)
 * 2. preparing - Preparing transaction (getting nonce, gas, etc.)
 * 3. confirm - Confirm transaction details with gas fees
 * 4. signing - TSS multi-party signing in progress
 * 5. broadcasting - Broadcasting signed transaction
 * 6. completed - Show transaction hash and explorer link
 * 7. error - Show error message
 *
 * Note: No password required - TSS wallets don't use passwords
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TransferScreen(
    wallet: ShareRecord,
    balance: String?,
    walletBalance: WalletBalance? = null,
    sessionStatus: SessionStatus,
    participants: List<String> = emptyList(),
    currentRound: Int = 0,
    totalRounds: Int = 9,
    preparedTx: TransactionUtils.PreparedTransaction? = null,
    signSessionId: String? = null,
    inviteCode: String? = null,
    signature: String? = null,
    txHash: String? = null,
    isLoading: Boolean = false,
    error: String? = null,
    networkType: NetworkType = NetworkType.MAINNET,
    rpcUrl: String = "https://evm.kava.io",
    onPrepareTransaction: (toAddress: String, amount: String, tokenType: TokenType) -> Unit,
    onConfirmTransaction: (includeServerBackup: Boolean) -> Unit,  // 新增参数：是否包含服务器备份参与签名
    onCopyInviteCode: () -> Unit,
    onBroadcastTransaction: () -> Unit,
    onCancel: () -> Unit,
    onBackToWallets: () -> Unit
) {
    var toAddress by remember { mutableStateOf("") }
    var amount by remember { mutableStateOf("") }
    var selectedTokenType by remember { mutableStateOf(TokenType.KAVA) }
    var validationError by remember { mutableStateOf<String?>(null) }

    // QR Scanner launcher for recipient address
    val scanLauncher = rememberLauncherForActivityResult(ScanContract()) { result ->
        result.contents?.let { scannedContent ->
            // Handle scanned address - may be plain address or EIP-681 URI
            val address = if (scannedContent.startsWith("ethereum:")) {
                // Parse EIP-681 URI: ethereum:0x...[@chainId][/function]?[params]
                scannedContent.removePrefix("ethereum:").split("@", "/", "?").firstOrNull() ?: scannedContent
            } else {
                scannedContent
            }
            // Only set if it looks like a valid address
            if (address.startsWith("0x") && address.length == 42) {
                toAddress = address
            } else {
                validationError = "扫描的不是有效的钱包地址"
            }
        }
    }

    // Determine current step
    val step = when {
        txHash != null -> "completed"
        signature != null -> "broadcasting"
        sessionStatus == SessionStatus.IN_PROGRESS -> "signing"
        signSessionId != null -> "signing"
        preparedTx != null && !isLoading -> "confirm"
        isLoading && preparedTx == null -> "preparing"
        error != null -> "error"
        else -> "input"
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) {
        // Top Bar
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            IconButton(onClick = onCancel) {
                Icon(Icons.Default.ArrowBack, contentDescription = "返回")
            }
            Text(
                text = "转账",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )
            Spacer(modifier = Modifier.width(48.dp))
        }

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

        when (step) {
            "input" -> TransferInputScreen(
                wallet = wallet,
                balance = balance,
                walletBalance = walletBalance,
                selectedTokenType = selectedTokenType,
                onTokenTypeChange = { selectedTokenType = it },
                toAddress = toAddress,
                onToAddressChange = { toAddress = it },
                amount = amount,
                onAmountChange = { amount = it },
                error = validationError ?: error,
                rpcUrl = rpcUrl,
                onSubmit = {
                    // Get current balance for the selected token type
                    val currentBalance = walletBalance?.getBalance(selectedTokenType)
                        ?: if (selectedTokenType == TokenType.KAVA) balance else null
                    when {
                        toAddress.isBlank() -> validationError = "请输入收款地址"
                        !toAddress.startsWith("0x") || toAddress.length != 42 -> validationError = "地址格式不正确"
                        amount.isBlank() -> validationError = "请输入金额"
                        amount.toDoubleOrNull() == null || amount.toDouble() <= 0 -> validationError = "金额无效"
                        currentBalance != null && amount.toDouble() > currentBalance.toDouble() -> validationError = "余额不足"
                        else -> {
                            validationError = null
                            onPrepareTransaction(toAddress.trim(), amount.trim(), selectedTokenType)
                        }
                    }
                },
                onCancel = onCancel,
                onScanQrCode = {
                    val options = ScanOptions().apply {
                        setDesiredBarcodeFormats(ScanOptions.QR_CODE)
                        setPrompt("扫描收款地址二维码")
                        setCameraId(0)
                        setBeepEnabled(true)
                        setBarcodeImageEnabled(false)
                        setOrientationLocked(true)
                        setCaptureActivity(PortraitCaptureActivity::class.java)
                    }
                    scanLauncher.launch(options)
                }
            )

            "preparing" -> PreparingScreen()

            "confirm" -> TransferConfirmScreen(
                wallet = wallet,
                preparedTx = preparedTx!!,
                toAddress = toAddress,
                amount = amount,
                error = error,
                onConfirm = { includeServerBackup ->
                    validationError = null
                    onConfirmTransaction(includeServerBackup)  // 传递服务器备份选项
                },
                onBack = onCancel
            )

            "signing" -> SigningScreen(
                wallet = wallet,
                sessionId = signSessionId ?: "",
                inviteCode = inviteCode,
                sessionStatus = sessionStatus,
                participants = participants,
                currentRound = currentRound,
                totalRounds = totalRounds,
                onCopyInviteCode = onCopyInviteCode
            )

            "broadcasting" -> BroadcastingScreen(
                isLoading = isLoading,
                onBroadcast = onBroadcastTransaction
            )

            "completed" -> CompletedScreen(
                txHash = txHash!!,
                toAddress = toAddress,
                amount = amount,
                networkType = networkType,
                onBackToWallets = onBackToWallets
            )

            "error" -> ErrorScreen(
                error = error ?: "未知错误",
                onRetry = onCancel,
                onBack = onBackToWallets
            )
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun TransferInputScreen(
    wallet: ShareRecord,
    balance: String?,
    walletBalance: WalletBalance?,
    selectedTokenType: TokenType,
    onTokenTypeChange: (TokenType) -> Unit,
    toAddress: String,
    onToAddressChange: (String) -> Unit,
    amount: String,
    onAmountChange: (String) -> Unit,
    error: String?,
    rpcUrl: String,
    onSubmit: () -> Unit,
    onCancel: () -> Unit,
    onScanQrCode: () -> Unit
) {
    val scope = rememberCoroutineScope()
    var isCalculatingMax by remember { mutableStateOf(false) }

    // Get current balance for the selected token type
    val currentBalance = walletBalance?.getBalance(selectedTokenType)
        ?: if (selectedTokenType == TokenType.KAVA) balance else null
    val tokenSymbol = TokenConfig.getName(selectedTokenType)

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        // From wallet info
        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.surfaceVariant
            )
        ) {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "从",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = wallet.address,
                    style = MaterialTheme.typography.bodyMedium,
                    fontFamily = FontFamily.Monospace,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis
                )
                Spacer(modifier = Modifier.height(8.dp))

                // Show all token balances in a 2x2 grid
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        // KAVA balance
                        Column {
                            Text(
                                text = "KAVA",
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Text(
                                text = walletBalance?.kavaBalance ?: balance ?: "加载中...",
                                style = MaterialTheme.typography.bodySmall,
                                fontWeight = FontWeight.Medium,
                                color = MaterialTheme.colorScheme.primary
                            )
                        }
                        // Green Points balance (绿积分)
                        Column(horizontalAlignment = Alignment.End) {
                            Text(
                                text = GreenPointsToken.NAME,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Text(
                                text = walletBalance?.greenPointsBalance ?: "加载中...",
                                style = MaterialTheme.typography.bodySmall,
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF4CAF50)
                            )
                        }
                    }
                    Spacer(modifier = Modifier.height(4.dp))
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        // Energy Points balance (积分股)
                        Column {
                            Text(
                                text = EnergyPointsToken.NAME,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Text(
                                text = walletBalance?.energyPointsBalance ?: "加载中...",
                                style = MaterialTheme.typography.bodySmall,
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF2196F3)  // Blue
                            )
                        }
                        // Future Points balance (积分值)
                        Column(horizontalAlignment = Alignment.End) {
                            Text(
                                text = FuturePointsToken.NAME,
                                style = MaterialTheme.typography.labelSmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Text(
                                text = walletBalance?.futurePointsBalance ?: "加载中...",
                                style = MaterialTheme.typography.bodySmall,
                                fontWeight = FontWeight.Medium,
                                color = Color(0xFF9C27B0)  // Purple
                            )
                        }
                    }
                }
            }
        }

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

        // Token type selector
        Text(
            text = "选择转账类型",
            style = MaterialTheme.typography.labelMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(8.dp))
        // First row: KAVA and Green Points
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // KAVA option
            FilterChip(
                selected = selectedTokenType == TokenType.KAVA,
                onClick = { onTokenTypeChange(TokenType.KAVA) },
                label = { Text("KAVA") },
                leadingIcon = {
                    if (selectedTokenType == TokenType.KAVA) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                },
                modifier = Modifier.weight(1f)
            )
            // Green Points option (绿积分)
            FilterChip(
                selected = selectedTokenType == TokenType.GREEN_POINTS,
                onClick = { onTokenTypeChange(TokenType.GREEN_POINTS) },
                label = { Text(GreenPointsToken.NAME) },
                leadingIcon = {
                    if (selectedTokenType == TokenType.GREEN_POINTS) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                },
                colors = FilterChipDefaults.filterChipColors(
                    selectedContainerColor = Color(0xFF4CAF50).copy(alpha = 0.2f),
                    selectedLabelColor = Color(0xFF4CAF50)
                ),
                modifier = Modifier.weight(1f)
            )
        }
        Spacer(modifier = Modifier.height(8.dp))
        // Second row: Energy Points and Future Points
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // Energy Points option (积分股)
            FilterChip(
                selected = selectedTokenType == TokenType.ENERGY_POINTS,
                onClick = { onTokenTypeChange(TokenType.ENERGY_POINTS) },
                label = { Text(EnergyPointsToken.NAME) },
                leadingIcon = {
                    if (selectedTokenType == TokenType.ENERGY_POINTS) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                },
                colors = FilterChipDefaults.filterChipColors(
                    selectedContainerColor = Color(0xFF2196F3).copy(alpha = 0.2f),
                    selectedLabelColor = Color(0xFF2196F3)
                ),
                modifier = Modifier.weight(1f)
            )
            // Future Points option (积分值)
            FilterChip(
                selected = selectedTokenType == TokenType.FUTURE_POINTS,
                onClick = { onTokenTypeChange(TokenType.FUTURE_POINTS) },
                label = { Text(FuturePointsToken.NAME) },
                leadingIcon = {
                    if (selectedTokenType == TokenType.FUTURE_POINTS) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                },
                colors = FilterChipDefaults.filterChipColors(
                    selectedContainerColor = Color(0xFF9C27B0).copy(alpha = 0.2f),
                    selectedLabelColor = Color(0xFF9C27B0)
                ),
                modifier = Modifier.weight(1f)
            )
        }

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

        // Recipient address with QR scan button
        OutlinedTextField(
            value = toAddress,
            onValueChange = onToAddressChange,
            label = { Text("收款地址") },
            placeholder = { Text("0x... 或点击扫码") },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            leadingIcon = {
                Icon(Icons.Default.Person, contentDescription = null)
            },
            trailingIcon = {
                IconButton(onClick = onScanQrCode) {
                    Icon(
                        Icons.Default.QrCodeScanner,
                        contentDescription = "扫描二维码",
                        tint = MaterialTheme.colorScheme.primary
                    )
                }
            }
        )

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

        // Amount with dynamic label based on token type
        OutlinedTextField(
            value = amount,
            onValueChange = onAmountChange,
            label = { Text("金额 ($tokenSymbol)") },
            placeholder = { Text("0.0") },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
            leadingIcon = {
                Icon(
                    if (selectedTokenType == TokenType.KAVA) Icons.Default.AttachMoney else Icons.Default.Stars,
                    contentDescription = null,
                    tint = when (selectedTokenType) {
                        TokenType.KAVA -> MaterialTheme.colorScheme.onSurfaceVariant
                        TokenType.GREEN_POINTS -> Color(0xFF4CAF50)
                        TokenType.ENERGY_POINTS -> Color(0xFF2196F3)
                        TokenType.FUTURE_POINTS -> Color(0xFF9C27B0)
                    }
                )
            },
            trailingIcon = {
                if (currentBalance != null) {
                    TextButton(
                        onClick = {
                            scope.launch {
                                isCalculatingMax = true
                                if (selectedTokenType == TokenType.KAVA) {
                                    // For KAVA, calculate max after deducting gas
                                    val result = TransactionUtils.calculateMaxTransferAmount(currentBalance, rpcUrl)
                                    result.onSuccess { maxAmount ->
                                        onAmountChange(maxAmount)
                                    }.onFailure {
                                        // Fallback to balance if calculation fails
                                        onAmountChange(currentBalance)
                                    }
                                } else {
                                    // For ERC-20 tokens (dUSDT, eUSDT, fUSDT), use the full balance
                                    onAmountChange(currentBalance)
                                }
                                isCalculatingMax = false
                            }
                        },
                        enabled = !isCalculatingMax
                    ) {
                        Text(
                            if (isCalculatingMax) "..." else "全部",
                            style = MaterialTheme.typography.labelSmall
                        )
                    }
                }
            }
        )

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

        // Info card
        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.secondaryContainer
            )
        ) {
            Row(
                modifier = Modifier.padding(12.dp),
                verticalAlignment = Alignment.Top
            ) {
                Icon(
                    Icons.Default.Info,
                    contentDescription = null,
                    modifier = Modifier.size(20.dp),
                    tint = MaterialTheme.colorScheme.onSecondaryContainer
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "转账需要 ${wallet.thresholdT} 个参与者共同签名。确认后将创建签名会话，其他参与者需要加入会话完成签名。",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }

        // Error display
        error?.let {
            Spacer(modifier = Modifier.height(16.dp))
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.Error,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.error
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = it,
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }
        }

        Spacer(modifier = Modifier.weight(1f))

        // Buttons
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = onCancel,
                modifier = Modifier.weight(1f)
            ) {
                Text("取消")
            }
            Button(
                onClick = onSubmit,
                modifier = Modifier.weight(1f)
            ) {
                Text("下一步")
            }
        }
    }
}

@Composable
private fun PreparingScreen() {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(horizontalAlignment = Alignment.CenterHorizontally) {
            CircularProgressIndicator(
                modifier = Modifier.size(48.dp),
                strokeWidth = 4.dp
            )
            Spacer(modifier = Modifier.height(16.dp))
            Text(
                text = "准备交易中...",
                style = MaterialTheme.typography.bodyLarge
            )
            Spacer(modifier = Modifier.height(8.dp))
            Text(
                text = "正在获取 Gas 价格和 Nonce",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun TransferConfirmScreen(
    wallet: ShareRecord,
    preparedTx: TransactionUtils.PreparedTransaction,
    toAddress: String,
    amount: String,
    error: String?,
    onConfirm: (includeServerBackup: Boolean) -> Unit,  // 新增参数：是否包含服务器备份参与签名
    onBack: () -> Unit
) {
    val gasFee = TransactionUtils.weiToKava(preparedTx.gasPrice.multiply(preparedTx.gasLimit))
    val gasGwei = TransactionUtils.weiToGwei(preparedTx.gasPrice)

    // 【新增】服务器备份选项状态（仅 2-of-3 时使用）
    var includeServerBackup by remember { mutableStateOf(false) }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        Text(
            text = "确认交易",
            style = MaterialTheme.typography.titleLarge,
            fontWeight = FontWeight.Bold
        )

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

        // Transaction summary card
        Card {
            Column(modifier = Modifier.padding(16.dp)) {
                // Amount
                Text(
                    text = "转账金额",
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
                Text(
                    text = "$amount KAVA",
                    style = MaterialTheme.typography.headlineMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary
                )

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

                // To address
                InfoRow("收款地址", toAddress.take(10) + "..." + toAddress.takeLast(8))

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

                // Gas info
                InfoRow("Gas 价格", "$gasGwei Gwei")
                Spacer(modifier = Modifier.height(4.dp))
                InfoRow("Gas 限制", preparedTx.gasLimit.toString())
                Spacer(modifier = Modifier.height(4.dp))
                InfoRow("预估手续费", "$gasFee KAVA")
                Spacer(modifier = Modifier.height(4.dp))
                InfoRow("Nonce", preparedTx.nonce.toString())
            }
        }

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

        // Threshold info
        Card(
            colors = CardDefaults.cardColors(
                containerColor = MaterialTheme.colorScheme.secondaryContainer
            )
        ) {
            Row(
                modifier = Modifier.padding(12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    Icons.Default.Group,
                    contentDescription = null,
                    modifier = Modifier.size(20.dp),
                    tint = MaterialTheme.colorScheme.onSecondaryContainer
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "此交易需要 ${wallet.thresholdT} 个参与者共同签名",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSecondaryContainer
                )
            }
        }

        // 【新增功能】2-of-3 服务器备份选项
        // 仅在 2-of-3 配置时显示此选项
        // 目的：允许用户在丢失一个设备时，使用服务器备份 + 剩余设备完成签名
        // 安全限制：仅 2-of-3 配置可用，其他配置（3-of-5, 4-of-7 等）不显示
        // 回滚方法：删除此代码块即可恢复原有行为
        if (wallet.thresholdT == 2 && wallet.thresholdN == 3) {
            Spacer(modifier = Modifier.height(16.dp))

            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.tertiaryContainer
                )
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Checkbox(
                        checked = includeServerBackup,
                        onCheckedChange = { includeServerBackup = it }
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Column {
                        Text(
                            text = "包含服务器备份参与签名",
                            style = MaterialTheme.typography.bodyMedium,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Text(
                            text = "如果您丢失了一个设备，勾选此项以使用服务器备份完成签名",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                    }
                }
            }
        }

        // Error display
        error?.let {
            Spacer(modifier = Modifier.height(16.dp))
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                )
            ) {
                Row(
                    modifier = Modifier.padding(12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.Error,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.error
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = it,
                        color = MaterialTheme.colorScheme.onErrorContainer,
                        style = MaterialTheme.typography.bodySmall
                    )
                }
            }
        }

        Spacer(modifier = Modifier.weight(1f))

        // Buttons
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = onBack,
                modifier = Modifier.weight(1f)
            ) {
                Text("返回")
            }
            Button(
                onClick = { onConfirm(includeServerBackup) },  // 传递服务器备份选项
                modifier = Modifier.weight(1f)
            ) {
                Icon(
                    Icons.Default.Send,
                    contentDescription = null,
                    modifier = Modifier.size(18.dp)
                )
                Spacer(modifier = Modifier.width(4.dp))
                Text("发起签名")
            }
        }
    }
}

@Composable
private fun SigningScreen(
    wallet: ShareRecord,
    sessionId: String,
    inviteCode: String?,
    sessionStatus: SessionStatus,
    participants: List<String>,
    currentRound: Int,
    totalRounds: Int,
    onCopyInviteCode: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
    ) {
        // Header with session ID
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "签名会话",
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold
            )

            // Status badge
            Surface(
                color = when (sessionStatus) {
                    SessionStatus.WAITING -> MaterialTheme.colorScheme.tertiaryContainer
                    SessionStatus.IN_PROGRESS -> MaterialTheme.colorScheme.primaryContainer
                    SessionStatus.COMPLETED -> Color(0xFFD4AF37) // Gold
                    SessionStatus.FAILED -> MaterialTheme.colorScheme.errorContainer
                },
                shape = MaterialTheme.shapes.small
            ) {
                Text(
                    text = when (sessionStatus) {
                        SessionStatus.WAITING -> "等待参与方"
                        SessionStatus.IN_PROGRESS -> "签名中"
                        SessionStatus.COMPLETED -> "完成"
                        SessionStatus.FAILED -> "失败"
                    },
                    modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                    style = MaterialTheme.typography.labelSmall
                )
            }
        }

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

        Text(
            text = "会话 ID: ${sessionId.take(16)}...",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

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

        // Invite code with QR code (if waiting)
        if (sessionStatus == SessionStatus.WAITING && inviteCode != null) {
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(
                    modifier = Modifier.padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "邀请码",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.fillMaxWidth()
                    )

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

                    // QR Code for invite code
                    val qrBitmap = remember(inviteCode) {
                        generateInviteQRCode(inviteCode, 200)
                    }
                    qrBitmap?.let { bitmap ->
                        Box(
                            modifier = Modifier
                                .size(200.dp)
                                .background(Color.White),
                            contentAlignment = Alignment.Center
                        ) {
                            Image(
                                bitmap = bitmap.asImageBitmap(),
                                contentDescription = "邀请码二维码",
                                modifier = Modifier.size(200.dp)
                            )
                        }
                    }

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

                    // Invite code text with copy button
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = inviteCode,
                            style = MaterialTheme.typography.bodyMedium,
                            fontFamily = FontFamily.Monospace,
                            modifier = Modifier.weight(1f)
                        )
                        Button(onClick = onCopyInviteCode) {
                            Text("复制")
                        }
                    }

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

                    Text(
                        text = "扫描二维码或分享邀请码给其他签名参与者",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }

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

        // Progress bar (if in progress)
        if (sessionStatus == SessionStatus.IN_PROGRESS) {
            Card {
                Column(modifier = Modifier.padding(16.dp)) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text(
                            text = "签名进度",
                            style = MaterialTheme.typography.titleSmall,
                            fontWeight = FontWeight.Medium
                        )
                        Text(
                            text = "$currentRound / $totalRounds",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                    Spacer(modifier = Modifier.height(8.dp))
                    LinearProgressIndicator(
                        progress = currentRound.toFloat() / totalRounds,
                        modifier = Modifier.fillMaxWidth()
                    )
                }
            }

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

        // Participants list
        Card {
            Column(modifier = Modifier.padding(16.dp)) {
                Text(
                    text = "签名参与者 (${participants.size} / ${wallet.thresholdT})",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.Medium
                )

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

                participants.forEachIndexed { index, name ->
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 4.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text(
                                text = "#${index + 1}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = name,
                                style = MaterialTheme.typography.bodyMedium
                            )
                        }
                        Icon(
                            Icons.Default.CheckCircle,
                            contentDescription = null,
                            tint = Color(0xFFD4AF37), // Gold
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }

                // Show empty slots
                for (i in participants.size until wallet.thresholdT) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 4.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text(
                                text = "#${i + 1}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = "等待加入...",
                                style = MaterialTheme.typography.bodyMedium,
                                color = MaterialTheme.colorScheme.outline
                            )
                        }
                        CircularProgressIndicator(
                            modifier = Modifier.size(16.dp),
                            strokeWidth = 2.dp
                        )
                    }
                }
            }
        }

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

        // Info text
        if (sessionStatus == SessionStatus.WAITING) {
            Text(
                text = "等待其他参与者加入后将自动开始签名...",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        } else if (sessionStatus == SessionStatus.IN_PROGRESS) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.Center,
                verticalAlignment = Alignment.CenterVertically
            ) {
                CircularProgressIndicator(
                    modifier = Modifier.size(16.dp),
                    strokeWidth = 2.dp
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "正在进行多方签名计算...",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

@Composable
private fun BroadcastingScreen(
    isLoading: Boolean,
    onBroadcast: () -> Unit
) {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Success icon
            Surface(
                modifier = Modifier.size(80.dp),
                shape = MaterialTheme.shapes.extraLarge,
                color = Color(0xFFD4AF37) // Gold
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        Icons.Default.Check,
                        contentDescription = null,
                        modifier = Modifier.size(40.dp),
                        tint = Color.Black
                    )
                }
            }

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

            Text(
                text = "签名完成!",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold
            )

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

            Text(
                text = "交易已签名，点击下方按钮广播到主网",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            Button(
                onClick = onBroadcast,
                enabled = !isLoading,
                modifier = Modifier.fillMaxWidth(0.8f)
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("广播中...")
                } else {
                    Icon(
                        Icons.Default.Send,
                        contentDescription = null,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("广播交易")
                }
            }
        }
    }
}

@Composable
private fun CompletedScreen(
    txHash: String,
    toAddress: String,
    amount: String,
    networkType: NetworkType,
    onBackToWallets: () -> Unit
) {
    val context = LocalContext.current

    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .verticalScroll(rememberScrollState()),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // Success icon
            Surface(
                modifier = Modifier.size(100.dp),
                shape = MaterialTheme.shapes.extraLarge,
                color = Color(0xFFD4AF37) // Gold
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        Icons.Default.CheckCircle,
                        contentDescription = null,
                        modifier = Modifier.size(60.dp),
                        tint = Color.Black
                    )
                }
            }

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

            Text(
                text = "交易已成功广播!",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold
            )

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

            Text(
                text = "向 ${toAddress.take(10)}...${toAddress.takeLast(8)} 转账 $amount KAVA",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            // Transaction hash card
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                ),
                modifier = Modifier.fillMaxWidth()
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "交易哈希",
                        style = MaterialTheme.typography.labelMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = txHash,
                        style = MaterialTheme.typography.bodySmall,
                        fontFamily = FontFamily.Monospace
                    )
                }
            }

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

            // View on explorer button
            OutlinedButton(
                onClick = {
                    val baseUrl = if (networkType == NetworkType.TESTNET) {
                        "https://testnet.kavascan.com"
                    } else {
                        "https://kavascan.com"
                    }
                    val url = "$baseUrl/tx/$txHash"
                    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                    context.startActivity(intent)
                },
                modifier = Modifier.fillMaxWidth()
            ) {
                Icon(
                    Icons.Default.OpenInNew,
                    contentDescription = null,
                    modifier = Modifier.size(18.dp)
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text("在 KavaScan 查看")
            }

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

            Button(
                onClick = onBackToWallets,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text("返回钱包列表")
            }
        }
    }
}

@Composable
private fun ErrorScreen(
    error: String,
    onRetry: () -> Unit,
    onBack: () -> Unit
) {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Column(
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Surface(
                modifier = Modifier.size(80.dp),
                shape = MaterialTheme.shapes.extraLarge,
                color = MaterialTheme.colorScheme.errorContainer
            ) {
                Box(contentAlignment = Alignment.Center) {
                    Icon(
                        Icons.Default.Error,
                        contentDescription = null,
                        modifier = Modifier.size(40.dp),
                        tint = MaterialTheme.colorScheme.error
                    )
                }
            }

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

            Text(
                text = "交易失败",
                style = MaterialTheme.typography.headlineSmall,
                fontWeight = FontWeight.Bold
            )

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

            Text(
                text = error,
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.error,
                textAlign = TextAlign.Center
            )

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

            Row(
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                OutlinedButton(onClick = onBack) {
                    Text("返回")
                }
                Button(onClick = onRetry) {
                    Text("重试")
                }
            }
        }
    }
}

@Composable
private fun InfoRow(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
        )
    }
}

/**
 * Generate QR code bitmap for invite code
 */
private fun generateInviteQRCode(content: String, size: Int): Bitmap? {
    return try {
        val writer = QRCodeWriter()
        val bitMatrix = writer.encode(content, BarcodeFormat.QR_CODE, size, size)
        val width = bitMatrix.width
        val height = bitMatrix.height
        val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565)
        for (x in 0 until width) {
            for (y in 0 until height) {
                bitmap.setPixel(x, y, if (bitMatrix[x, y]) android.graphics.Color.BLACK else android.graphics.Color.WHITE)
            }
        }
        bitmap
    } catch (e: Exception) {
        null
    }
}
