package com.tsmobile.app.ui.screens

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DarkMode
import androidx.compose.material.icons.filled.LightMode
import androidx.compose.material.icons.filled.SettingsBrightness
import androidx.compose.material.icons.filled.Dns
import androidx.compose.material.icons.filled.SystemUpdate
import com.tsmobile.app.ui.theme.ThemeMode
import com.tsmobile.app.ui.theme.UiTokens
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.text.font.FontWeight
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
import com.tsmobile.app.data.RecentConnection
import com.tsmobile.app.ui.components.ConnectButton
import com.tsmobile.app.ui.components.UpdateCheckDialog
import com.tsmobile.app.viewmodel.ConnectState
import com.tsmobile.app.viewmodel.ServerViewModel
import com.tsmobile.app.viewmodel.formatRelativeTime

/**
 * 服务器配置页。
 * 三段式布局：品牌区 / 输入区 / 最近连接列表。
 */
@Composable
fun ServerConfigScreen(
    viewModel: ServerViewModel,
    onNavigateToChannelList: () -> Unit, // 连接成功后跳转
) {
    val state by viewModel.state.collectAsState()
    val recents by viewModel.recents.collectAsState()
    val themeMode by viewModel.themeMode.collectAsState()

    Column(
        modifier = Modifier
            .fillMaxSize()
            .systemBarsPadding(),
    ) {
        // 上：品牌区
        BrandSection(
            themeMode = themeMode,
            onToggleTheme = { viewModel.toggleTheme() },
            isCheckingUpdate = state.isCheckingUpdate,
            onCheckUpdate = { viewModel.manualCheckUpdate() },
        )

        // 中：输入区
        InputSection(
            address = state.address,
            nickname = state.nickname,
            password = state.password,
            onAddressChange = viewModel::updateAddress,
            onNicknameChange = viewModel::updateNickname,
            onPasswordChange = viewModel::updatePassword,
            connectState = state.connectState,
            errorMessage = state.errorMessage,
            onConnect = { viewModel.connect() },
        )

        // 下：最近连接
        RecentConnectionsSection(
            recents = recents,
            enabled = state.connectState != ConnectState.CONNECTING,
            onConnectRecent = { recent -> viewModel.quickConnect(recent) },
            onRemoveRecent = { recent -> viewModel.removeRecent(recent) },
            onClearAll = { viewModel.clearRecents() },
        )
    }

    // 连接成功后自动跳转
    LaunchedEffect(state.connectState) {
        if (state.connectState == ConnectState.SUCCESS) {
            onNavigateToChannelList()
        }
    }

    // 手动检查更新弹窗
    val updateCheckResult by viewModel.updateCheckResult.collectAsState()
    updateCheckResult?.let { result ->
        UpdateCheckDialog(
            result = result,
            onDownload = { url -> viewModel.openReleaseUrl(url) },
            onDismissVersion = { viewModel.dismissUpdate() },
            onRetry = { viewModel.manualCheckUpdate() },
            onClose = { viewModel.closeUpdateDialog() },
        )
    }
}

/**
 * 品牌区组件。
 */
@Composable
private fun BrandSection(
    themeMode: ThemeMode,
    onToggleTheme: () -> Unit,
    isCheckingUpdate: Boolean = false,
    onCheckUpdate: () -> Unit = {},
) {
    Box(modifier = Modifier.fillMaxWidth()) {
        Column(
            modifier = Modifier.align(Alignment.Center),
            horizontalAlignment = Alignment.CenterHorizontally,
        ) {
            // Logo（使用 drawable 资源或 placeholder）
            Icon(
                imageVector = Icons.Default.Dns, // 临时图标
                contentDescription = "TeamSpeak",
                modifier = Modifier.size(72.dp),
                tint = MaterialTheme.colorScheme.primary,
            )
            Spacer(Modifier.height(12.dp))
            Text(
                text = "TeamSpeak Mobile",
                style = MaterialTheme.typography.headlineMedium,
                fontWeight = FontWeight.Bold,
            )
            Text(
                text = "连接到你的 TeamSpeak 服务器",
                style = MaterialTheme.typography.bodyMedium,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }

        // 检查更新按钮（左上角）
        IconButton(
            onClick = onCheckUpdate,
            enabled = !isCheckingUpdate,
            modifier = Modifier
                .align(Alignment.TopStart)
                .padding(start = 8.dp),
        ) {
            if (isCheckingUpdate) {
                CircularProgressIndicator(
                    modifier = Modifier.size(UiTokens.Size.IconMedium),
                    strokeWidth = UiTokens.Border.Emphasized,
                )
            } else {
                Icon(
                    imageVector = Icons.Default.SystemUpdate,
                    contentDescription = "检查更新",
                    tint = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }

        // 主题切换按钮（右上角）
        IconButton(
            onClick = onToggleTheme,
            modifier = Modifier
                .align(Alignment.TopEnd)
                .padding(end = 8.dp),
        ) {
            Icon(
                imageVector = when (themeMode) {
                    ThemeMode.LIGHT -> Icons.Default.LightMode
                    ThemeMode.DARK -> Icons.Default.DarkMode
                    ThemeMode.SYSTEM -> Icons.Default.SettingsBrightness
                },
                contentDescription = when (themeMode) {
                    ThemeMode.LIGHT -> "亮色主题"
                    ThemeMode.DARK -> "暗色主题"
                    ThemeMode.SYSTEM -> "跟随系统"
                },
            )
        }
    }
}

/**
 * 输入区组件。
 */
@Composable
private fun InputSection(
    address: String,
    nickname: String,
    password: String,
    onAddressChange: (String) -> Unit,
    onNicknameChange: (String) -> Unit,
    onPasswordChange: (String) -> Unit,
    connectState: ConnectState,
    errorMessage: String?,
    onConnect: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 16.dp),
    ) {
        // 服务器地址
        OutlinedTextField(
            value = address,
            onValueChange = onAddressChange,
            label = { Text("服务器地址") },
            placeholder = { Text("ts.example.com") },
            singleLine = true,
            isError = connectState == ConnectState.FAILED && address.isBlank(),
            modifier = Modifier.fillMaxWidth(),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
        )

        Spacer(Modifier.height(12.dp))

        // 昵称
        OutlinedTextField(
            value = nickname,
            onValueChange = onNicknameChange,
            label = { Text("昵称") },
            placeholder = { Text("我的昵称") },
            singleLine = true,
            isError = connectState == ConnectState.FAILED && nickname.isBlank(),
            modifier = Modifier.fillMaxWidth(),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Next),
        )

        Spacer(Modifier.height(12.dp))

        // 密码（可选）
        OutlinedTextField(
            value = password,
            onValueChange = onPasswordChange,
            label = { Text("密码（可选）") },
            placeholder = { Text("••••••") },
            singleLine = true,
            visualTransformation = PasswordVisualTransformation(),
            modifier = Modifier.fillMaxWidth(),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
        )

        Spacer(Modifier.height(24.dp))

        // 连接按钮（状态机驱动）
        ConnectButton(
            state = connectState,
            errorMessage = errorMessage,
            onClick = onConnect,
        )
    }
}

/**
 * 最近连接列表组件。
 */
@Composable
private fun RecentConnectionsSection(
    recents: List<RecentConnection>,
    enabled: Boolean,
    onConnectRecent: (RecentConnection) -> Unit,
    onRemoveRecent: (RecentConnection) -> Unit,
    onClearAll: () -> Unit,
) {
    if (recents.isEmpty()) return

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 24.dp, vertical = 8.dp),
    ) {
        Text(
            text = "最近连接",
            style = MaterialTheme.typography.titleSmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
        )
        Spacer(Modifier.height(8.dp))

        recents.forEach { recent ->
            RecentConnectionItem(
                recent = recent,
                enabled = enabled,
                onClick = { onConnectRecent(recent) },
                onLongClick = { onRemoveRecent(recent) },
            )
            Spacer(Modifier.height(4.dp))
        }

        Spacer(Modifier.height(8.dp))
        TextButton(
            onClick = onClearAll,
            modifier = Modifier.align(Alignment.CenterHorizontally),
        ) {
            Text("清空最近记录")
        }
    }
}

/**
 * 单条最近连接记录。
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun RecentConnectionItem(
    recent: RecentConnection,
    enabled: Boolean,
    onClick: () -> Unit,
    onLongClick: () -> Unit,
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clip(MaterialTheme.shapes.medium)
            .combinedClickable(
                enabled = enabled,
                onClick = onClick,
                onLongClick = onLongClick,
            ),
    ) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            // 状态指示灯
            Box(
                modifier = Modifier
                    .size(8.dp)
                    .background(
                        color = if (recent.lastSucceeded)
                            MaterialTheme.colorScheme.primary
                        else
                            MaterialTheme.colorScheme.error,
                        shape = CircleShape,
                    ),
            )
            Spacer(Modifier.width(12.dp))
            Column {
                Text(
                    text = recent.address,
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Medium,
                )
                Text(
                    text = "${recent.nickname} · ${formatRelativeTime(recent.lastConnectedAt)}",
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }
    }
}
