package com.durian.tssparty.presentation.screens

import android.app.Activity
import androidx.activity.compose.rememberLauncherForActivityResult
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.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.durian.tssparty.domain.model.SessionStatus
import com.durian.tssparty.domain.model.ShareRecord
import com.journeyapps.barcodescanner.ScanContract
import com.journeyapps.barcodescanner.ScanOptions

/**
 * Sign session info returned from validateSignInviteCode API
 * Matches service-party-app SignSessionInfo type
 */
data class SignSessionInfo(
    val sessionId: String,
    val keygenSessionId: String,
    val walletName: String,
    val messageHash: String,
    val thresholdT: Int,
    val thresholdN: Int,
    val currentParticipants: Int
)

/**
 * Format countdown seconds to mm:ss display
 */
private fun formatCountdown(seconds: Long): String {
    if (seconds < 0) return ""
    val minutes = seconds / 60
    val secs = seconds % 60
    return "%d:%02d".format(minutes, secs)
}

/**
 * CoSign Join screen matching service-party-app/src/renderer/src/pages/Sign.tsx
 * Flow: input → select_share → joining → signing → completed
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CoSignJoinScreen(
    shares: List<ShareRecord>,
    sessionStatus: SessionStatus,
    isLoading: Boolean,
    error: String?,
    signSessionInfo: SignSessionInfo? = null,
    participants: List<String> = emptyList(),
    currentRound: Int = 0,
    totalRounds: Int = 9,
    signature: String? = null,
    countdownSeconds: Long = -1L,  // 5-minute countdown: -1 = not counting, >0 = remaining seconds
    onValidateInviteCode: (inviteCode: String) -> Unit,
    onJoinSign: (inviteCode: String, shareId: Long, password: String) -> Unit,
    onCancel: () -> Unit,
    onResetState: () -> Unit = {},  // Reset ViewModel state without navigating
    onBackToHome: () -> Unit = {}
) {
    val context = LocalContext.current

    var inviteCode by remember { mutableStateOf("") }
    var selectedShareId by remember { mutableStateOf<Long?>(null) }
    var password by remember { mutableStateOf("") }
    var showPassword by remember { mutableStateOf(false) }
    var validationError by remember { mutableStateOf<String?>(null) }

    // Flow: input → select_share → joining → signing → completed
    var step by remember { mutableStateOf("input") }
    var autoJoinAttempted by remember { mutableStateOf(false) }

    // QR Code Scanner
    val scanLauncher = rememberLauncherForActivityResult(ScanContract()) { result ->
        if (result.contents != null) {
            // Extract invite code from scanned content
            val scannedCode = result.contents.let { content ->
                // Handle both raw invite codes and URLs
                if (content.contains("/")) {
                    content.substringAfterLast("/")
                } else {
                    content
                }
            }
            inviteCode = scannedCode.uppercase()
            // Auto-validate after scan
            if (inviteCode.isNotBlank()) {
                validationError = null
                onValidateInviteCode(inviteCode)
            }
        }
    }

    // Reset to input state (used by cancel buttons in select_share/joining/signing screens)
    val resetToInput: () -> Unit = {
        step = "input"
        inviteCode = ""
        selectedShareId = null
        password = ""
        validationError = null
        autoJoinAttempted = false
        onResetState() // Clear ViewModel state without navigating
    }

    // Handle session info received (validation success)
    LaunchedEffect(signSessionInfo) {
        if (signSessionInfo != null && step == "input") {
            step = "select_share"

            // Auto-select matching share
            val matchingShare = shares.find { it.sessionId == signSessionInfo.keygenSessionId }
            if (matchingShare != null) {
                selectedShareId = matchingShare.id
            } else if (shares.size == 1) {
                // Auto-select if only one share
                selectedShareId = shares.first().id
            }
        }
    }

    // Handle session status changes
    LaunchedEffect(sessionStatus) {
        when (sessionStatus) {
            SessionStatus.IN_PROGRESS -> {
                step = "signing"
            }
            SessionStatus.COMPLETED -> {
                step = "completed"
            }
            SessionStatus.FAILED -> {
                if (step == "joining" || step == "signing") {
                    step = "select_share"
                    autoJoinAttempted = false
                }
            }
            else -> {}
        }
    }

    // Reset auto-join on error
    LaunchedEffect(error) {
        if (error != null && (step == "joining" || step == "signing")) {
            step = "select_share"
            autoJoinAttempted = false
        }
    }

    when (step) {
        "input" -> InputScreen(
            inviteCode = inviteCode,
            isLoading = isLoading,
            error = error,
            validationError = validationError,
            onInviteCodeChange = { inviteCode = it.uppercase() },
            onValidateCode = {
                when {
                    inviteCode.isBlank() -> validationError = "请输入邀请码"
                    else -> {
                        validationError = null
                        onValidateInviteCode(inviteCode)
                    }
                }
            },
            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)
            },
            onCancel = onCancel  // In input state, cancel navigates away
        )
        "select_share" -> SelectShareScreen(
            shares = shares,
            signSessionInfo = signSessionInfo,
            selectedShareId = selectedShareId,
            password = password,
            showPassword = showPassword,
            isLoading = isLoading,
            error = error,
            validationError = validationError,
            onShareSelected = { selectedShareId = it },
            onPasswordChange = { password = it },
            onTogglePassword = { showPassword = !showPassword },
            onBack = {
                step = "input"
                autoJoinAttempted = false
                validationError = null
            },
            onJoinSign = {
                when {
                    selectedShareId == null -> validationError = "请选择一个钱包"
                    else -> {
                        validationError = null
                        autoJoinAttempted = true
                        step = "joining"
                        onJoinSign(inviteCode, selectedShareId!!, password)
                    }
                }
            },
            onCancel = resetToInput
        )
        "joining" -> JoiningScreen(
            countdownSeconds = countdownSeconds,
            onCancel = resetToInput
        )  // Reset to input state, stay on page
        "signing" -> SigningProgressScreen(
            sessionStatus = sessionStatus,
            participants = participants,
            currentRound = currentRound,
            totalRounds = totalRounds,
            countdownSeconds = countdownSeconds,
            onCancel = resetToInput  // Reset to input state, stay on page
        )
        "completed" -> SigningCompletedScreen(
            signature = signature,
            onBackToHome = onBackToHome
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun InputScreen(
    inviteCode: String,
    isLoading: Boolean,
    error: String?,
    validationError: String?,
    onInviteCodeChange: (String) -> Unit,
    onValidateCode: () -> Unit,
    onScanQrCode: () -> Unit,
    onCancel: () -> Unit
) {
    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))

        // QR Code Scan Button
        OutlinedButton(
            onClick = onScanQrCode,
            modifier = Modifier.fillMaxWidth(),
            enabled = !isLoading
        ) {
            Icon(Icons.Default.QrCodeScanner, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("扫描签名邀请码")
        }

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

        // Divider with "or" text
        Row(
            modifier = Modifier.fillMaxWidth(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Divider(modifier = Modifier.weight(1f))
            Text(
                text = "  或手动输入  ",
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            Divider(modifier = Modifier.weight(1f))
        }

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

        // Invite Code Input
        OutlinedTextField(
            value = inviteCode,
            onValueChange = onInviteCodeChange,
            label = { Text("邀请码") },
            placeholder = { Text("粘贴邀请码或邀请链接") },
            leadingIcon = {
                Icon(Icons.Default.QrCode, contentDescription = null)
            },
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            enabled = !isLoading
        )

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

        // Error display
        error?.let {
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                ),
                modifier = Modifier.fillMaxWidth()
            ) {
                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
                    )
                }
            }
            Spacer(modifier = Modifier.height(16.dp))
        }

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

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

        // Buttons
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            OutlinedButton(
                onClick = onCancel,
                modifier = Modifier.weight(1f),
                enabled = !isLoading
            ) {
                Text("取消")
            }

            Button(
                onClick = onValidateCode,
                modifier = Modifier.weight(1f),
                enabled = !isLoading && inviteCode.isNotBlank()
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("验证中...")
                } else {
                    Text("下一步")
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SelectShareScreen(
    shares: List<ShareRecord>,
    signSessionInfo: SignSessionInfo?,
    selectedShareId: Long?,
    password: String,
    showPassword: Boolean,
    isLoading: Boolean,
    error: String?,
    validationError: String?,
    onShareSelected: (Long) -> Unit,
    onPasswordChange: (String) -> Unit,
    onTogglePassword: () -> Unit,
    onBack: () -> Unit,
    onJoinSign: () -> Unit,
    onCancel: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        // Header
        Text(
            text = "加入多方签名",
            style = MaterialTheme.typography.headlineMedium,
            fontWeight = FontWeight.Bold
        )

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

        // Session info card
        if (signSessionInfo != null) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "签名会话信息",
                        style = MaterialTheme.typography.titleSmall,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    InfoRow("钱包名称", signSessionInfo.walletName)
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    InfoRow("签名阈值", "${signSessionInfo.thresholdT}-of-${signSessionInfo.thresholdN}")
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    InfoRow("消息哈希", "${signSessionInfo.messageHash.take(16)}...")
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    InfoRow("当前参与者", "${signSessionInfo.currentParticipants} / ${signSessionInfo.thresholdT}")
                }
            }
        }

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

        // Select Wallet
        Text(
            text = "选择本地钱包",
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold
        )

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

        if (shares.isEmpty()) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(24.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Icon(
                        Icons.Default.AccountBalanceWallet,
                        contentDescription = null,
                        modifier = Modifier.size(48.dp),
                        tint = MaterialTheme.colorScheme.outline
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    Text(
                        text = "暂无可用钱包",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.outline
                    )
                    Text(
                        text = "请先创建或加入一个密钥生成会话",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.outline
                    )
                }
            }
        } else {
            // Wallet selection cards
            shares.forEach { share ->
                val isSelected = selectedShareId == share.id
                val isMatching = signSessionInfo?.keygenSessionId == share.sessionId

                Card(
                    onClick = { onShareSelected(share.id) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(vertical = 4.dp),
                    colors = CardDefaults.cardColors(
                        containerColor = if (isSelected)
                            MaterialTheme.colorScheme.primaryContainer
                        else
                            MaterialTheme.colorScheme.surface
                    ),
                    border = if (isSelected)
                        CardDefaults.outlinedCardBorder()
                    else
                        null
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        RadioButton(
                            selected = isSelected,
                            onClick = { onShareSelected(share.id) }
                        )

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

                        Column(modifier = Modifier.weight(1f)) {
                            Row(verticalAlignment = Alignment.CenterVertically) {
                                Text(
                                    text = share.address.take(10) + "..." + share.address.takeLast(8),
                                    style = MaterialTheme.typography.bodyMedium,
                                    maxLines = 1,
                                    overflow = TextOverflow.Ellipsis,
                                    fontWeight = if (isSelected) FontWeight.SemiBold else FontWeight.Normal
                                )
                                if (isMatching) {
                                    Spacer(modifier = Modifier.width(8.dp))
                                    Surface(
                                        color = MaterialTheme.colorScheme.primary,
                                        shape = MaterialTheme.shapes.small
                                    ) {
                                        Text(
                                            text = "匹配",
                                            style = MaterialTheme.typography.labelSmall,
                                            color = MaterialTheme.colorScheme.onPrimary,
                                            modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp)
                                        )
                                    }
                                }
                            }
                            Spacer(modifier = Modifier.height(4.dp))
                            Text(
                                text = "${share.thresholdT}-of-${share.thresholdN} | Party #${share.partyIndex}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }

                        if (isSelected) {
                            Icon(
                                Icons.Default.CheckCircle,
                                contentDescription = null,
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                }
            }
        }

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

        // Password Input (optional)
        OutlinedTextField(
            value = password,
            onValueChange = onPasswordChange,
            label = { Text("钱包密码 (可选)") },
            placeholder = { Text("如果设置了密码，请输入") },
            leadingIcon = {
                Icon(Icons.Default.Lock, contentDescription = null)
            },
            trailingIcon = {
                IconButton(onClick = onTogglePassword) {
                    Icon(
                        imageVector = if (showPassword) Icons.Default.VisibilityOff else Icons.Default.Visibility,
                        contentDescription = null
                    )
                }
            },
            visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(),
            modifier = Modifier.fillMaxWidth(),
            singleLine = true,
            enabled = !isLoading
        )

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

        // Error display
        error?.let {
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.errorContainer
                ),
                modifier = Modifier.fillMaxWidth()
            ) {
                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
                    )
                }
            }
            Spacer(modifier = Modifier.height(16.dp))
        }

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

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

        // Buttons - Three buttons: Cancel, Back, Join
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            OutlinedButton(
                onClick = onCancel,
                modifier = Modifier.weight(1f),
                enabled = !isLoading
            ) {
                Text("取消")
            }

            OutlinedButton(
                onClick = onBack,
                modifier = Modifier.weight(1f),
                enabled = !isLoading
            ) {
                Text("返回")
            }

            Button(
                onClick = onJoinSign,
                modifier = Modifier.weight(1f),
                enabled = !isLoading && shares.isNotEmpty() && selectedShareId != null
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("加入中...")
                } else {
                    Icon(Icons.Default.Create, contentDescription = null)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text("加入签名")
                }
            }
        }
    }
}

@Composable
private fun JoiningScreen(
    countdownSeconds: Long = -1L,
    onCancel: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        CircularProgressIndicator(
            modifier = Modifier.size(80.dp),
            strokeWidth = 6.dp
        )

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

        Text(
            text = "正在加入签名会话...",
            style = MaterialTheme.typography.headlineSmall,
            fontWeight = FontWeight.Bold
        )

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

        Text(
            text = "请稍候，正在连接到其他签名参与者",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

        // Countdown timer (if counting down)
        if (countdownSeconds > 0) {
            Spacer(modifier = Modifier.height(24.dp))
            Card(
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.tertiaryContainer
                )
            ) {
                Row(
                    modifier = Modifier.padding(horizontal = 24.dp, vertical = 12.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.Timer,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onTertiaryContainer,
                        modifier = Modifier.size(20.dp)
                    )
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(
                        text = "等待启动: ${formatCountdown(countdownSeconds)}",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onTertiaryContainer
                    )
                }
            }
        }

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

        OutlinedButton(onClick = onCancel) {
            Icon(Icons.Default.Cancel, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("取消")
        }
    }
}

@Composable
private fun SigningProgressScreen(
    sessionStatus: SessionStatus,
    participants: List<String>,
    currentRound: Int,
    totalRounds: Int,
    countdownSeconds: Long = -1L,
    onCancel: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 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(32.dp))

        // Progress indicator
        CircularProgressIndicator(
            modifier = Modifier.size(80.dp),
            strokeWidth = 6.dp
        )

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

        // Progress card
        Card(modifier = Modifier.fillMaxWidth()) {
            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 = if (totalRounds > 0) currentRound.toFloat() / totalRounds else 0f,
                    modifier = Modifier.fillMaxWidth()
                )
            }
        }

        // Countdown timer (if counting down - waiting for sign to start)
        if (countdownSeconds > 0) {
            Spacer(modifier = Modifier.height(16.dp))
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.tertiaryContainer
                )
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalArrangement = Arrangement.Center,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Icon(
                        Icons.Default.Timer,
                        contentDescription = null,
                        tint = MaterialTheme.colorScheme.onTertiaryContainer,
                        modifier = Modifier.size(24.dp)
                    )
                    Spacer(modifier = Modifier.width(12.dp))
                    Column {
                        Text(
                            text = "等待签名启动",
                            style = MaterialTheme.typography.labelMedium,
                            color = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                        Text(
                            text = formatCountdown(countdownSeconds),
                            style = MaterialTheme.typography.headlineMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                    }
                }
            }
        }

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

        // Participants card
        if (participants.isNotEmpty()) {
            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "签名参与方 (${participants.size})",
                        style = MaterialTheme.typography.titleSmall,
                        fontWeight = FontWeight.Medium
                    )
                    Spacer(modifier = Modifier.height(8.dp))
                    participants.forEach { participant ->
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 4.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.Person,
                                contentDescription = null,
                                modifier = Modifier.size(20.dp),
                                tint = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.width(8.dp))
                            Text(
                                text = participant,
                                style = MaterialTheme.typography.bodyMedium
                            )
                            Spacer(modifier = Modifier.weight(1f))
                            Icon(
                                Icons.Default.CheckCircle,
                                contentDescription = null,
                                modifier = Modifier.size(16.dp),
                                tint = MaterialTheme.colorScheme.primary
                            )
                        }
                    }
                }
            }
        }

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

        // Cancel button
        OutlinedButton(onClick = onCancel) {
            Icon(Icons.Default.Cancel, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            Text("取消")
        }
    }
}

@Composable
private fun SigningCompletedScreen(
    signature: String?,
    onBackToHome: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        // Success icon
        Icon(
            Icons.Default.CheckCircle,
            contentDescription = null,
            modifier = Modifier.size(80.dp),
            tint = MaterialTheme.colorScheme.primary
        )

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

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

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

        Text(
            text = "多方签名已成功完成",
            style = MaterialTheme.typography.bodyMedium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )

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

        // Signature info
        if (signature != null) {
            Card(
                modifier = Modifier.fillMaxWidth(),
                colors = CardDefaults.cardColors(
                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                )
            ) {
                Column(modifier = Modifier.padding(16.dp)) {
                    Text(
                        text = "签名结果",
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(4.dp))
                    Text(
                        text = "${signature.take(32)}...${signature.takeLast(32)}",
                        style = MaterialTheme.typography.bodySmall,
                        fontWeight = FontWeight.Medium
                    )
                }
            }
        }

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

        Button(
            onClick = onBackToHome,
            modifier = Modifier.fillMaxWidth()
        ) {
            Icon(Icons.Default.Home, contentDescription = null)
            Spacer(modifier = Modifier.width(8.dp))
            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
        )
    }
}
