package com.tsmobile.app.ui.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.LinkOff
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.tsmobile.app.data.ConnectionState
import com.tsmobile.app.data.ServerInfo
import com.tsmobile.app.ui.theme.UiTokens

@Composable
fun ServerDetailCard(
    serverInfo: ServerInfo?,
    serverName: String,
    serverAddress: String,
    connectionState: ConnectionState?,
    onDisconnect: () -> Unit,
    onDismiss: () -> Unit,
) {
    var showDisconnectDialog by remember { mutableStateOf(false) }

    ModalDrawerSheet {
        Column(modifier = Modifier.fillMaxSize()) {
            // ═══ 顶部：服务器名称 + 地址 + 关闭按钮 ═══
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(
                        start = UiTokens.Spacing.Large,
                        end = UiTokens.Spacing.Small,
                        top = UiTokens.Spacing.Large,
                        bottom = UiTokens.Spacing.Medium,
                    ),
                verticalAlignment = Alignment.CenterVertically,
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = serverName.ifEmpty { "服务器详情" },
                        style = MaterialTheme.typography.headlineSmall,
                        fontWeight = FontWeight.Bold,
                    )
                    if (serverAddress.isNotEmpty()) {
                        Spacer(Modifier.height(UiTokens.Spacing.ExtraSmall))
                        Text(
                            text = serverAddress,
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }
                IconButton(onClick = onDismiss) {
                    Icon(Icons.Default.Close, contentDescription = "关闭")
                }
            }

            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)

            // ═══ 中部：欢迎消息 + 服务器信息（可滚动） ═══
            Column(
                modifier = Modifier
                    .weight(1f)
                    .verticalScroll(rememberScrollState())
                    .padding(UiTokens.Spacing.Large),
                verticalArrangement = Arrangement.spacedBy(UiTokens.Spacing.Medium),
            ) {
                // 欢迎消息
                if (serverInfo != null && serverInfo.welcomeMessage.isNotEmpty()) {
                    SectionCard(title = "欢迎消息") {
                        Text(
                            text = serverInfo.welcomeMessage,
                            style = MaterialTheme.typography.bodySmall,
                        )
                    }
                }

                // 服务器详细信息
                SectionCard(title = "服务器信息") {
                    ServerInfoContent(serverInfo, connectionState)
                }
            }

            // ═══ 底部：断开连接按钮 ═══
            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
            OutlinedButton(
                onClick = { showDisconnectDialog = true },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(UiTokens.Spacing.Large),
                colors = ButtonDefaults.outlinedButtonColors(
                    contentColor = MaterialTheme.colorScheme.error
                ),
            ) {
                Icon(Icons.Default.LinkOff, contentDescription = null)
                Spacer(Modifier.width(UiTokens.Spacing.Small))
                Text("断开连接")
            }
        }
    }

    if (showDisconnectDialog) {
        DisconnectConfirmDialog(
            onConfirm = { showDisconnectDialog = false; onDisconnect() },
            onDismiss = { showDisconnectDialog = false },
        )
    }
}

@Composable
private fun SectionCard(
    title: String,
    content: @Composable ColumnScope.() -> Unit,
) {
    Surface(
        modifier = Modifier.fillMaxWidth(),
        shape = MaterialTheme.shapes.medium,
        color = MaterialTheme.colorScheme.surfaceVariant,
        tonalElevation = UiTokens.Elevation.Raised,
    ) {
        Column(modifier = Modifier.padding(UiTokens.Spacing.Medium)) {
            Text(
                text = title,
                style = MaterialTheme.typography.labelLarge,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
                fontWeight = FontWeight.Medium,
            )
            Spacer(Modifier.height(UiTokens.Spacing.Small))
            content()
        }
    }
}

@Composable
private fun ServerInfoContent(
    serverInfo: ServerInfo?,
    connectionState: ConnectionState?,
) {
    Column(verticalArrangement = Arrangement.spacedBy(UiTokens.Spacing.Small)) {
        DetailInfoRow("状态", when (connectionState) {
            is ConnectionState.Connected -> "已连接"
            is ConnectionState.Disconnecting -> "断开中..."
            is ConnectionState.WaitingForNetwork -> "等待网络恢复..."
            is ConnectionState.Reconnecting -> "重连中 (${connectionState.attempt}/${connectionState.maxAttempts})"
            is ConnectionState.Disconnected -> "已断开"
            null -> "未连接"
        })
        if (serverInfo == null) {
            Text(
                "正在加载服务器信息...",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        } else {
            DetailInfoRow("在线人数", "${serverInfo.clientsOnline} / ${serverInfo.maxClients}")
            DetailInfoRow("频道数", "${serverInfo.channelsOnline}")
            if (serverInfo.version.isNotEmpty()) DetailInfoRow("版本", serverInfo.version)
            if (serverInfo.platform.isNotEmpty()) DetailInfoRow("平台", serverInfo.platform)
            (serverInfo.uptime.toLongOrNull() ?: 0).takeIf { it > 0 }?.let {
                DetailInfoRow("运行时长", formatUptime(it))
            }
        }
    }
}

private fun formatUptime(seconds: Long): String {
    val days = seconds / 86400
    val hours = (seconds % 86400) / 3600
    val minutes = (seconds % 3600) / 60
    return when {
        days > 0 -> "${days}天${hours}小时"
        hours > 0 -> "${hours}小时${minutes}分钟"
        else -> "${minutes}分钟"
    }
}
