package com.tsmobile.app.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Warning
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.tsmobile.app.data.ConnectionState
import com.tsmobile.app.ui.theme.UiTokens
import com.tsmobile.app.ui.theme.semanticColors

/**
 * 重连横幅 — 显示在频道列表页顶部。
 *
 * 对应 docs/UI架构设计.md 5.4 断线重连：
 * "自动重连：最多尝试 5 次，间隔递增（2s → 4s → 8s → 16s → 30s）"
 */
@Composable
fun ReconnectBanner(
    reconnectState: ConnectionState.Reconnecting,
    onManualReconnect: () -> Unit,
    onAbandon: () -> Unit,
) {
    val semanticColors = MaterialTheme.semanticColors
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = semanticColors.warningContainer,
        contentColor = semanticColors.onWarningContainer,
        tonalElevation = UiTokens.Elevation.Subtle,
    ) {
        Column(
            modifier = Modifier.padding(
                horizontal = UiTokens.Spacing.Large,
                vertical = UiTokens.Spacing.Medium,
            ),
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    imageVector = Icons.Default.Warning,
                    contentDescription = null,
                    tint = semanticColors.warning,
                    modifier = Modifier.size(UiTokens.Size.IconMedium),
                )
                Spacer(Modifier.width(UiTokens.Spacing.Small))
                Text(
                    text = "连接已断开",
                    style = MaterialTheme.typography.labelLarge,
                )
            }

            Spacer(Modifier.height(UiTokens.Spacing.ExtraSmall))
            Text(
                text = "正在尝试重连... (${reconnectState.attempt}/${reconnectState.maxAttempts})",
                style = MaterialTheme.typography.bodySmall,
            )

            if (reconnectState.reason.isNotEmpty()) {
                Text(
                    text = reconnectState.reason,
                    style = MaterialTheme.typography.bodySmall,
                    color = semanticColors.onWarningContainer.copy(alpha = 0.7f),
                )
            }

            Spacer(Modifier.height(UiTokens.Spacing.Small))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,
            ) {
                TextButton(onClick = onManualReconnect) {
                    Text("手动重连")
                }
                TextButton(
                    onClick = onAbandon,
                    colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error),
                ) {
                    Text("放弃")
                }
            }
        }
    }
}

/**
 * 等待网络横幅 — 网络丢失后等待恢复。
 *
 * 显示"网络已断开"提示，自动等待网络恢复后重连。
 * 用户可手动触发重连或放弃等待。
 */
@Composable
fun WaitingForNetworkBanner(
    onManualReconnect: () -> Unit,
    onAbandon: () -> Unit,
) {
    val semanticColors = MaterialTheme.semanticColors
    Surface(
        modifier = Modifier.fillMaxWidth(),
        color = semanticColors.warningContainer,
        contentColor = semanticColors.onWarningContainer,
        tonalElevation = UiTokens.Elevation.Subtle,
    ) {
        Column(
            modifier = Modifier.padding(
                horizontal = UiTokens.Spacing.Large,
                vertical = UiTokens.Spacing.Medium,
            ),
        ) {
            Row(verticalAlignment = Alignment.CenterVertically) {
                Icon(
                    imageVector = Icons.Default.Warning,
                    contentDescription = null,
                    tint = semanticColors.warning,
                    modifier = Modifier.size(UiTokens.Size.IconMedium),
                )
                Spacer(Modifier.width(UiTokens.Spacing.Small))
                Text(
                    text = "网络已断开",
                    style = MaterialTheme.typography.labelLarge,
                )
            }

            Spacer(Modifier.height(UiTokens.Spacing.ExtraSmall))
            Text(
                text = "等待网络恢复后自动重连...",
                style = MaterialTheme.typography.bodySmall,
            )

            Spacer(Modifier.height(UiTokens.Spacing.Small))
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.End,
            ) {
                TextButton(onClick = onManualReconnect) {
                    Text("手动重连")
                }
                TextButton(
                    onClick = onAbandon,
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error,
                    ),
                ) {
                    Text("放弃")
                }
            }
        }
    }
}

/**
 * 重连全屏遮罩 — 覆盖整个界面，阻止用户操作。
 *
 * 在重连/等待网络期间显示，包含加载动画、重连进度、放弃按钮。
 * 遮罩层消费所有点击事件，防止用户在重连期间触发任何操作。
 */
@Composable
fun ReconnectOverlay(
    connectionState: ConnectionState,
    onAbandon: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val title: String
    val subtitle: String
    val detail: String?

    when (connectionState) {
        is ConnectionState.WaitingForNetwork -> {
            title = "网络已断开"
            subtitle = "等待网络恢复后自动重连..."
            detail = null
        }
        is ConnectionState.Reconnecting -> {
            title = "正在重连..."
            subtitle = "第 ${connectionState.attempt}/${connectionState.maxAttempts} 次尝试"
            detail = connectionState.reason.takeIf { it.isNotEmpty() }
        }
        else -> return // 仅在等待网络或重连时显示
    }

    Box(
        modifier = modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.5f))
            .clickable(
                indication = null,
                interactionSource = remember { MutableInteractionSource() },
            ) {
                // 消费所有点击事件，阻止穿透到下层 UI
            },
        contentAlignment = Alignment.Center,
    ) {
        Card(
            modifier = Modifier
                .width(280.dp)
                .padding(horizontal = UiTokens.Spacing.Large),
            elevation = CardDefaults.cardElevation(defaultElevation = 6.dp),
        ) {
            Column(
                modifier = Modifier
                    .padding(UiTokens.Spacing.Large)
                    .heightIn(min = 200.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center,
            ) {
                CircularProgressIndicator()

                Spacer(Modifier.height(UiTokens.Spacing.Medium))

                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    textAlign = TextAlign.Center,
                )

                Spacer(Modifier.height(UiTokens.Spacing.Small))

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

                // 为 detail 预留固定高度空间，避免文本出现/消失导致卡片跳动
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 32.dp),
                    contentAlignment = Alignment.Center,
                ) {
                    if (detail != null) {
                        Text(
                            text = detail,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
                            textAlign = TextAlign.Center,
                            maxLines = 2,
                        )
                    }
                }

                Spacer(Modifier.height(UiTokens.Spacing.Large))

                Row(horizontalArrangement = Arrangement.Center) {
                    TextButton(
                        onClick = onAbandon,
                        colors = ButtonDefaults.textButtonColors(
                            contentColor = MaterialTheme.colorScheme.error,
                        ),
                    ) {
                        Text("放弃")
                    }
                }
            }
        }
    }
}
