package com.durian.tssparty.presentation.screens

import androidx.compose.animation.*
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.durian.tssparty.domain.model.AppReadyState
import com.durian.tssparty.domain.model.AppState
import com.durian.tssparty.domain.model.ServiceStatus

@Composable
fun StartupCheckScreen(
    appState: AppState,
    onEnterApp: () -> Unit,
    onRetry: () -> Unit
) {
    val canEnter = appState.appReady == AppReadyState.READY || appState.appReady == AppReadyState.ERROR

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(MaterialTheme.colorScheme.background)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(24.dp),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            // App Logo/Icon
            Box(
                modifier = Modifier
                    .size(100.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.primaryContainer),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    imageVector = Icons.Default.Lock,
                    contentDescription = null,
                    modifier = Modifier.size(50.dp),
                    tint = MaterialTheme.colorScheme.onPrimaryContainer
                )
            }

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

            // App Title
            Text(
                text = "TSS Party",
                style = MaterialTheme.typography.headlineLarge,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground
            )

            Text(
                text = "多方安全计算钱包",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )

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

            // Service Check Cards
            Card(
                modifier = Modifier.fillMaxWidth(),
                shape = RoundedCornerShape(16.dp)
            ) {
                Column(
                    modifier = Modifier.padding(16.dp)
                ) {
                    Text(
                        text = "服务状态",
                        style = MaterialTheme.typography.titleMedium,
                        fontWeight = FontWeight.SemiBold
                    )

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

                    // Database Status
                    ServiceCheckItem(
                        icon = Icons.Default.Storage,
                        title = "本地数据库",
                        status = appState.environment.database,
                        extraInfo = if (appState.walletCount > 0) "${appState.walletCount} 个钱包" else null
                    )

                    Divider(modifier = Modifier.padding(vertical = 12.dp))

                    // Message Router Status
                    ServiceCheckItem(
                        icon = Icons.Default.Cloud,
                        title = "消息路由服务",
                        status = appState.environment.messageRouter,
                        extraInfo = appState.partyId?.take(8)?.let { "Party: $it..." }
                    )

                    Divider(modifier = Modifier.padding(vertical = 12.dp))

                    // Kava API Status
                    ServiceCheckItem(
                        icon = Icons.Default.Language,
                        title = "Kava 区块链",
                        status = appState.environment.kavaApi,
                        extraInfo = appState.environment.kavaApi.latency?.let { "${it}ms" }
                    )
                }
            }

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

            // Status Message
            when (appState.appReady) {
                AppReadyState.INITIALIZING -> {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(20.dp),
                            strokeWidth = 2.dp
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Text(
                            text = "正在检查服务...",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
                AppReadyState.READY -> {
                    Text(
                        text = "所有服务就绪",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.primary
                    )
                }
                AppReadyState.ERROR -> {
                    Text(
                        text = appState.appError ?: "部分服务不可用",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.error,
                        textAlign = TextAlign.Center
                    )
                }
            }

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

            // Action Buttons
            Row(
                horizontalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                if (appState.appReady == AppReadyState.ERROR) {
                    OutlinedButton(
                        onClick = onRetry,
                        modifier = Modifier.weight(1f)
                    ) {
                        Icon(
                            Icons.Default.Refresh,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("重试")
                    }
                }

                Button(
                    onClick = onEnterApp,
                    enabled = canEnter,
                    modifier = Modifier.weight(1f)
                ) {
                    Text(
                        text = when (appState.appReady) {
                            AppReadyState.READY -> "进入应用"
                            AppReadyState.ERROR -> "继续使用"
                            else -> "加载中..."
                        }
                    )
                    if (canEnter) {
                        Spacer(modifier = Modifier.width(8.dp))
                        Icon(
                            Icons.Default.ArrowForward,
                            contentDescription = null,
                            modifier = Modifier.size(18.dp)
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun ServiceCheckItem(
    icon: ImageVector,
    title: String,
    status: ServiceStatus,
    extraInfo: String? = null
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically
    ) {
        // Icon with status indicator
        Box {
            Icon(
                imageVector = icon,
                contentDescription = null,
                modifier = Modifier.size(32.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant
            )
            // Status dot
            Box(
                modifier = Modifier
                    .size(12.dp)
                    .align(Alignment.BottomEnd)
                    .clip(CircleShape)
                    .background(
                        when {
                            status.message.isEmpty() -> Color.Gray
                            status.isOnline -> Color(0xFFD4AF37) // Gold for success
                            else -> Color(0xFFFF5722)
                        }
                    )
            )
        }

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

        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = title,
                style = MaterialTheme.typography.bodyLarge,
                fontWeight = FontWeight.Medium
            )
            if (status.message.isNotEmpty()) {
                Text(
                    text = status.message,
                    style = MaterialTheme.typography.bodySmall,
                    color = if (status.isOnline)
                        MaterialTheme.colorScheme.onSurfaceVariant
                    else
                        MaterialTheme.colorScheme.error
                )
            }
        }

        // Extra info (wallet count, latency, etc.)
        extraInfo?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.primary
            )
        }
    }
}
