package com.example.gameofmoon.presentation.ui.components

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.*
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
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.draw.drawBehind
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import com.example.gameofmoon.ui.theme.GameofMoonTheme
import androidx.compose.ui.graphics.Color

// 基本赛博朋克色彩定义
private val CyberBlue = Color(0xFF00FFFF)
private val CyberGreen = Color(0xFF39FF14)
private val DarkBackground = Color(0xFF0A0A0A)
private val DarkSurface = Color(0xFF151515)
private val DarkCard = Color(0xFF1E1E1E)
private val DarkBorder = Color(0xFF333333)
private val TextPrimary = Color(0xFFE0E0E0)
private val TextSecondary = Color(0xFFB0B0B0)
private val TextDisabled = Color(0xFF606060)
private val TextAccent = Color(0xFF00FFFF)
private val ErrorRed = Color(0xFFFF0040)
private val WarningOrange = Color(0xFFFF8800)
private val SuccessGreen = Color(0xFF00FF88)
private val ScanlineColor = Color(0x1100FFFF)

// 字体样式定义
object CyberTextStyles {
    val Terminal = androidx.compose.ui.text.TextStyle(
        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
        fontWeight = androidx.compose.ui.text.font.FontWeight.Normal,
        fontSize = 12.sp,
        lineHeight = 18.sp,
        letterSpacing = 0.5.sp
    )
    
    val Caption = androidx.compose.ui.text.TextStyle(
        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
        fontWeight = androidx.compose.ui.text.font.FontWeight.Light,
        fontSize = 10.sp,
        lineHeight = 16.sp,
        letterSpacing = 0.2.sp
    )
    
    val DataDisplay = androidx.compose.ui.text.TextStyle(
        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
        fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
        fontSize = 16.sp,
        lineHeight = 24.sp,
        letterSpacing = 1.0.sp
    )
    
    val Choice = androidx.compose.ui.text.TextStyle(
        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
        fontWeight = androidx.compose.ui.text.font.FontWeight.Medium,
        fontSize = 13.sp,
        lineHeight = 20.sp,
        letterSpacing = 0.3.sp
    )
    
    val StoryContent = androidx.compose.ui.text.TextStyle(
        fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace,
        fontWeight = androidx.compose.ui.text.font.FontWeight.Normal,
        fontSize = 14.sp,
        lineHeight = 24.sp,
        letterSpacing = 0.25.sp
    )
}

/**
 * 赛博朋克风格的终端窗口组件
 */
@Composable
fun TerminalWindow(
    title: String,
    modifier: Modifier = Modifier,
    isActive: Boolean = true,
    content: @Composable BoxScope.() -> Unit
) {
    val borderColor by animateColorAsState(
        targetValue = if (isActive) CyberBlue else DarkBorder,
        animationSpec = tween(300),
        label = "border_color"
    )
    
    Box(
        modifier = modifier
            .fillMaxWidth()
            .background(DarkBackground)
            .border(1.dp, borderColor)
            .background(DarkSurface.copy(alpha = 0.9f))
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(DarkCard)
                .padding(horizontal = 12.dp, vertical = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = title,
                style = CyberTextStyles.Terminal,
                color = if (isActive) CyberBlue else TextSecondary
            )
            
            Row(
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                // 终端控制按钮
                repeat(3) { index ->
                    val color = when (index) {
                        0 -> ErrorRed
                        1 -> WarningOrange
                        else -> SuccessGreen
                    }
                    Box(
                        modifier = Modifier
                            .size(8.dp)
                            .background(color, RoundedCornerShape(50))
                    )
                }
            }
        }
        
        // 内容区域
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(top = 36.dp) // 为标题栏留出空间
                .padding(12.dp)
        ) {
            content()
        }
        
        // 扫描线效果
        if (isActive) {
            ScanlineEffect()
        }
    }
}

/**
 * 扫描线效果组件
 */
@Composable
private fun BoxScope.ScanlineEffect() {
    val infiniteTransition = rememberInfiniteTransition(label = "scanline")
    val scanlinePosition by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(2000, easing = LinearEasing),
            repeatMode = RepeatMode.Restart
        ),
        label = "scanline_position"
    )
    
    Box(
        modifier = Modifier
            .fillMaxSize()
            .drawBehind {
                val scanlineY = size.height * scanlinePosition
                drawLine(
                    color = ScanlineColor,
                    start = Offset(0f, scanlineY),
                    end = Offset(size.width, scanlineY),
                    strokeWidth = 2.dp.toPx()
                )
            }
    )
}

/**
 * 霓虹发光按钮
 */
@Composable
fun NeonButton(
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    enabled: Boolean = true,
    colors: ButtonColors = ButtonDefaults.buttonColors(
        containerColor = Color.Transparent,
        contentColor = CyberBlue,
        disabledContainerColor = Color.Transparent,
        disabledContentColor = TextDisabled
    ),
    glowColor: Color = CyberBlue,
    content: @Composable RowScope.() -> Unit
) {
    val animatedGlow by animateFloatAsState(
        targetValue = if (enabled) 1f else 0.3f,
        animationSpec = tween(300),
        label = "glow_animation"
    )
    
    Button(
        onClick = onClick,
        modifier = modifier
            .drawBehind {
                // 外发光效果
                val glowRadius = 8.dp.toPx()
                val glowAlpha = 0.6f * animatedGlow
                
                drawRoundRect(
                    color = glowColor.copy(alpha = glowAlpha),
                    size = size,
                    style = Stroke(width = 2.dp.toPx()),
                    cornerRadius = androidx.compose.ui.geometry.CornerRadius(4.dp.toPx())
                )
                
                // 内边框
                drawRoundRect(
                    color = glowColor.copy(alpha = 0.8f * animatedGlow),
                    size = size,
                    style = Stroke(width = 1.dp.toPx()),
                    cornerRadius = androidx.compose.ui.geometry.CornerRadius(4.dp.toPx())
                )
            },
        enabled = enabled,
        colors = colors,
        shape = RoundedCornerShape(4.dp),
        border = BorderStroke(1.dp, glowColor.copy(alpha = animatedGlow)),
        content = content
    )
}

/**
 * 数据显示面板
 */
@Composable
fun DataPanel(
    label: String,
    value: String,
    modifier: Modifier = Modifier,
    valueColor: Color = CyberBlue,
    icon: @Composable (() -> Unit)? = null,
    trend: DataTrend? = null
) {
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = DarkCard,
            contentColor = TextPrimary
        ),
        border = BorderStroke(1.dp, DarkBorder)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column {
                Text(
                    text = label,
                    style = CyberTextStyles.Caption,
                    color = TextSecondary
                )
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Text(
                        text = value,
                        style = CyberTextStyles.DataDisplay,
                        color = valueColor
                    )
                    trend?.let { TrendIndicator(it) }
                }
            }
            icon?.invoke()
        }
    }
}

/**
 * 数据趋势枚举
 */
enum class DataTrend {
    UP, DOWN, STABLE
}

/**
 * 趋势指示器
 */
@Composable
private fun TrendIndicator(trend: DataTrend) {
    val (color, symbol) = when (trend) {
        DataTrend.UP -> SuccessGreen to "↑"
        DataTrend.DOWN -> ErrorRed to "↓"
        DataTrend.STABLE -> TextSecondary to "→"
    }
    
    Text(
        text = symbol,
        style = CyberTextStyles.Caption,
        color = color
    )
}

/**
 * 进度条组件
 */
@Composable
fun CyberProgressBar(
    progress: Float,
    modifier: Modifier = Modifier,
    progressColor: Color = CyberGreen,
    backgroundColor: Color = DarkBorder,
    showPercentage: Boolean = true,
    animated: Boolean = true
) {
    val animatedProgress by animateFloatAsState(
        targetValue = if (animated) progress else progress,
        animationSpec = tween(500),
        label = "progress_animation"
    )
    
    Column(modifier = modifier) {
        if (showPercentage) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    text = "${(progress * 100).toInt()}%",
                    style = CyberTextStyles.Caption,
                    color = progressColor
                )
            }
        }
        
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .height(8.dp)
                .background(backgroundColor, RoundedCornerShape(4.dp))
        ) {
            Box(
                modifier = Modifier
                    .fillMaxHeight()
                    .fillMaxWidth(animatedProgress.coerceIn(0f, 1f))
                    .background(
                        brush = Brush.horizontalGradient(
                            colors = listOf(
                                progressColor.copy(alpha = 0.6f),
                                progressColor,
                                progressColor.copy(alpha = 0.8f)
                            )
                        ),
                        shape = RoundedCornerShape(4.dp)
                    )
                    .drawBehind {
                        // 发光效果
                        drawRect(
                            color = progressColor.copy(alpha = 0.3f),
                            size = size
                        )
                    }
            )
        }
    }
}

/**
 * 信息卡片
 */
@Composable
fun InfoCard(
    title: String,
    content: String,
    modifier: Modifier = Modifier,
    icon: @Composable (() -> Unit)? = null,
    accentColor: Color = CyberBlue,
    onClick: (() -> Unit)? = null
) {
    val interactionSource = remember { MutableInteractionSource() }
    
    Card(
        modifier = modifier
            .fillMaxWidth()
            .then(
                if (onClick != null) {
                    Modifier.clickable(
                        interactionSource = interactionSource,
                        indication = null
                    ) { onClick() }
                } else Modifier
            ),
        colors = CardDefaults.cardColors(
            containerColor = DarkCard,
            contentColor = TextPrimary
        ),
        border = BorderStroke(1.dp, accentColor.copy(alpha = 0.5f))
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.Top,
            horizontalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            icon?.invoke()
            
            Column(
                modifier = Modifier.weight(1f),
                verticalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                Text(
                    text = title,
                    style = CyberTextStyles.Choice,
                    color = accentColor
                )
                Text(
                    text = content,
                    style = CyberTextStyles.StoryContent,
                    color = TextPrimary,
                    overflow = TextOverflow.Ellipsis
                )
            }
        }
    }
}

/**
 * 状态指示器
 */
@Composable
fun StatusIndicator(
    label: String,
    status: StatusType,
    modifier: Modifier = Modifier
) {
    val (color, icon) = when (status) {
        StatusType.ONLINE -> SuccessGreen to "●"
        StatusType.OFFLINE -> ErrorRed to "●"
        StatusType.WARNING -> WarningOrange to "●"
        StatusType.PROCESSING -> CyberBlue to "●"
    }
    
    val animatedAlpha by animateFloatAsState(
        targetValue = if (status == StatusType.PROCESSING) 0.5f else 1f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000),
            repeatMode = RepeatMode.Reverse
        ),
        label = "status_blink"
    )
    
    Row(
        modifier = modifier,
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        Text(
            text = icon,
            style = CyberTextStyles.Terminal,
            color = color.copy(alpha = if (status == StatusType.PROCESSING) animatedAlpha else 1f)
        )
        Text(
            text = label,
            style = CyberTextStyles.Caption,
            color = TextSecondary
        )
    }
}

/**
 * 状态类型枚举
 */
enum class StatusType {
    ONLINE, OFFLINE, WARNING, PROCESSING
}

/**
 * 分隔线组件
 */
@Composable
fun CyberDivider(
    modifier: Modifier = Modifier,
    color: Color = DarkBorder,
    thickness: Float = 1f,
    animated: Boolean = false
) {
    if (animated) {
        val infiniteTransition = rememberInfiniteTransition(label = "divider_animation")
        val animatedAlpha by infiniteTransition.animateFloat(
            initialValue = 0.3f,
            targetValue = 1f,
            animationSpec = infiniteRepeatable(
                animation = tween(2000),
                repeatMode = RepeatMode.Reverse
            ),
            label = "divider_alpha"
        )
        
        Box(
            modifier = modifier
                .fillMaxWidth()
                .height(thickness.dp)
                .background(color.copy(alpha = animatedAlpha))
        )
    } else {
        Box(
            modifier = modifier
                .fillMaxWidth()
                .height(thickness.dp)
                .background(color)
        )
    }
}

/**
 * 专用的故事内容窗口组件
 * 解决BoxScope和ColumnScope作用域冲突问题
 * 专门为故事内容和选择按钮设计
 */
@Composable
fun StoryContentWindow(
    title: String,
    modifier: Modifier = Modifier,
    isActive: Boolean = true,
    content: @Composable ColumnScope.() -> Unit
) {
    val borderColor by animateColorAsState(
        targetValue = if (isActive) CyberBlue else DarkBorder,
        animationSpec = tween(300),
        label = "border_color"
    )
    
    Column(
        modifier = modifier
            .fillMaxWidth()
            .background(DarkBackground)
            .border(1.dp, borderColor)
            .background(DarkSurface.copy(alpha = 0.9f))
    ) {
        // 标题栏
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .background(DarkCard)
                .padding(horizontal = 12.dp, vertical = 8.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = title,
                style = CyberTextStyles.Terminal,
                color = if (isActive) CyberBlue else TextSecondary
            )
            
            Row(
                horizontalArrangement = Arrangement.spacedBy(4.dp)
            ) {
                // 终端控制按钮
                repeat(3) { index ->
                    val color = when (index) {
                        0 -> ErrorRed
                        1 -> WarningOrange
                        else -> SuccessGreen
                    }
                    Box(
                        modifier = Modifier
                            .size(8.dp)
                            .background(color, RoundedCornerShape(50))
                    )
                }
            }
        }
        
        // 内容区域 - 直接使用Column作用域
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f) // 自动填充剩余空间
                .padding(12.dp)
                .verticalScroll(rememberScrollState())
        ) {
            content()
        }
        
        // 扫描线效果覆盖层
        if (isActive) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(2.dp)
                    .background(
                        Brush.horizontalGradient(
                            colors = listOf(
                                Color.Transparent,
                                ScanlineColor,
                                Color.Transparent
                            )
                        )
                    )
            )
        }
    }
}

