package com.tsmobile.app.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.tsmobile.app.ui.theme.UiTokens
import com.tsmobile.app.ui.theme.semanticColors
import com.tsmobile.app.viewmodel.ConnectState

/**
 * 连接按钮状态机组件。
 * 根据 ConnectState 显示不同的外观和行为。
 */
@Composable
fun ConnectButton(
    state: ConnectState,
    errorMessage: String?,
    onClick: () -> Unit,
) {
    val colors = MaterialTheme.colorScheme
    val semanticColors = MaterialTheme.semanticColors
    val buttonColors = when (state) {
        ConnectState.FAILED -> ButtonDefaults.buttonColors(
            containerColor = colors.errorContainer,
            contentColor = colors.onErrorContainer,
        )
        ConnectState.TIMEOUT -> ButtonDefaults.buttonColors(
            containerColor = semanticColors.warningContainer,
            contentColor = semanticColors.onWarningContainer,
        )
        else -> ButtonDefaults.buttonColors()
    }

    Button(
        onClick = onClick,
        enabled = state != ConnectState.CONNECTING,
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(min = UiTokens.Size.TouchTarget),
        colors = buttonColors,
        elevation = ButtonDefaults.buttonElevation(defaultElevation = UiTokens.Elevation.Subtle),
    ) {
        when (state) {
            ConnectState.IDLE -> Text("连接服务器")
            ConnectState.CONNECTING -> {
                CircularProgressIndicator(
                    modifier = Modifier.size(UiTokens.Size.IconMedium),
                    strokeWidth = UiTokens.Border.Emphasized,
                    color = colors.onSurface.copy(alpha = 0.5f),
                )
                Spacer(Modifier.width(UiTokens.Spacing.Small))
                Text("连接中...")
            }
            ConnectState.SUCCESS -> { /* 不会到达，自动跳转 */ }
            ConnectState.FAILED -> Text(errorMessage ?: "连接失败，点击重试")
            ConnectState.TIMEOUT -> Text("连接超时，点击重试")
        }
    }
}
