package com.tsmobile.app.ui.components

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
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.CheckCircle
import androidx.compose.material.icons.filled.Error
import androidx.compose.material.icons.filled.NewReleases
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.tsmobile.app.ui.theme.UiTokens
import com.tsmobile.app.viewmodel.UpdateInfo

/**
 * 手动检查更新的结果状态。
 */
sealed class UpdateCheckResult {
    /** 正在检查中 */
    data object Checking : UpdateCheckResult()
    /** 发现新版本 */
    data class UpdateAvailable(val info: UpdateInfo) : UpdateCheckResult()
    /** 已经是最新版 */
    data object NoUpdate : UpdateCheckResult()
    /** 检查失败 */
    data class Error(val message: String) : UpdateCheckResult()
}

/**
 * 更新检查弹窗。
 *
 * 点击"检查更新"后弹出，显示检查过程和结果。
 * - 检查中：旋转进度 + "正在检查更新..."
 * - 有新版本：版本号 + 下载/忽略按钮
 * - 无更新：绿色对勾 + "已经是最新版"
 * - 失败：错误图标 + 错误信息 + 重试/关闭按钮
 */
@Composable
fun UpdateCheckDialog(
    result: UpdateCheckResult,
    onDownload: (String) -> Unit,
    onDismissVersion: () -> Unit,
    onRetry: () -> Unit,
    onClose: () -> Unit,
) {
    AlertDialog(
        onDismissRequest = { if (result !is UpdateCheckResult.Checking) onClose() },
        shape = MaterialTheme.shapes.extraLarge,
        tonalElevation = UiTokens.Elevation.Floating,
        title = {
            Row(verticalAlignment = Alignment.CenterVertically) {
                when (result) {
                    is UpdateCheckResult.Checking -> {
                        CircularProgressIndicator(
                            modifier = Modifier.size(UiTokens.Size.IconMedium),
                            strokeWidth = UiTokens.Border.Emphasized,
                        )
                        Spacer(Modifier.width(UiTokens.Spacing.Medium))
                        Text("检查更新")
                    }
                    is UpdateCheckResult.UpdateAvailable -> {
                        Icon(
                            imageVector = Icons.Default.NewReleases,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(UiTokens.Size.IconMedium),
                        )
                        Spacer(Modifier.width(UiTokens.Spacing.Medium))
                        Text("发现新版本")
                    }
                    is UpdateCheckResult.NoUpdate -> {
                        Icon(
                            imageVector = Icons.Default.CheckCircle,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.primary,
                            modifier = Modifier.size(UiTokens.Size.IconMedium),
                        )
                        Spacer(Modifier.width(UiTokens.Spacing.Medium))
                        Text("检查完成")
                    }
                    is UpdateCheckResult.Error -> {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = null,
                            tint = MaterialTheme.colorScheme.error,
                            modifier = Modifier.size(UiTokens.Size.IconMedium),
                        )
                        Spacer(Modifier.width(UiTokens.Spacing.Medium))
                        Text("检查失败")
                    }
                }
            }
        },
        text = {
            Column {
                AnimatedVisibility(
                    visible = result is UpdateCheckResult.Checking,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    Text(
                        text = "正在连接服务器检查更新...",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }

                AnimatedVisibility(
                    visible = result is UpdateCheckResult.UpdateAvailable,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    val info = (result as? UpdateCheckResult.UpdateAvailable)?.info
                    if (info != null) {
                        Column {
                            Text(
                                text = "新版本 ${info.versionName} 已发布",
                                style = MaterialTheme.typography.bodyMedium,
                            )
                            Spacer(Modifier.height(UiTokens.Spacing.ExtraSmall))
                            Text(
                                text = "建议下载最新版本以获得更好的体验。",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant,
                            )

                            // 更新内容（支持滚动）
                            if (info.body.isNotBlank()) {
                                Spacer(Modifier.height(UiTokens.Spacing.Medium))
                                Surface(
                                    color = MaterialTheme.colorScheme.surfaceContainerLow,
                                    shape = MaterialTheme.shapes.small,
                                ) {
                                    Column(
                                        modifier = Modifier
                                            .heightIn(max = 200.dp)
                                            .verticalScroll(rememberScrollState())
                                            .padding(UiTokens.Spacing.Medium),
                                    ) {
                                        Text(
                                            text = "更新内容",
                                            style = MaterialTheme.typography.labelMedium,
                                            color = MaterialTheme.colorScheme.primary,
                                        )
                                        Spacer(Modifier.height(UiTokens.Spacing.ExtraSmall))
                                        Text(
                                            text = info.body,
                                            style = MaterialTheme.typography.bodySmall,
                                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                                        )
                                    }
                                }
                            }
                        }
                    }
                }

                AnimatedVisibility(
                    visible = result is UpdateCheckResult.NoUpdate,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    Text(
                        text = "已经是最新版，无需更新。",
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }

                AnimatedVisibility(
                    visible = result is UpdateCheckResult.Error,
                    enter = fadeIn(),
                    exit = fadeOut(),
                ) {
                    val msg = (result as? UpdateCheckResult.Error)?.message ?: ""
                    Text(
                        text = msg.ifBlank { "网络连接失败，请稍后重试" },
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.error,
                    )
                }
            }
        },
        confirmButton = {
            when (result) {
                is UpdateCheckResult.Checking -> {
                    // 检查中不显示按钮
                }
                is UpdateCheckResult.UpdateAvailable -> {
                    TextButton(
                        onClick = { onDismissVersion() },
                    ) {
                        Text("忽略此版本")
                    }
                    Spacer(Modifier.width(UiTokens.Spacing.Small))
                    Button(
                        onClick = { onDownload(result.info.releaseUrl) },
                    ) {
                        Text("下载更新")
                    }
                }
                is UpdateCheckResult.NoUpdate -> {
                    Button(onClick = onClose) {
                        Text("确定")
                    }
                }
                is UpdateCheckResult.Error -> {
                    TextButton(onClick = onClose) {
                        Text("关闭")
                    }
                    Spacer(Modifier.width(UiTokens.Spacing.Small))
                    Button(onClick = onRetry) {
                        Text("重试")
                    }
                }
            }
        },
        dismissButton = {
            if (result is UpdateCheckResult.UpdateAvailable ||
                result is UpdateCheckResult.Error
            ) {
                // 关闭按钮在 confirmButton 区域已处理
            }
        },
    )
}
