package com.example.gameofmoon.presentation.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.layout.statusBarsPadding
import com.example.gameofmoon.data.GameSaveManager
import com.example.gameofmoon.data.SimpleGeminiService
import com.example.gameofmoon.data.GameContext
import com.example.gameofmoon.model.*
import com.example.gameofmoon.story.CompleteStoryData
import com.example.gameofmoon.presentation.ui.components.*
import kotlinx.coroutines.launch

@Composable
fun TimeCageGameScreen() {
    val context = LocalContext.current
    val saveManager = remember { GameSaveManager(context) }
    val geminiService = remember { SimpleGeminiService() }
    val coroutineScope = rememberCoroutineScope()
    
    var gameState by remember { mutableStateOf(GameState()) }
    var currentNode by remember { 
        mutableStateOf(
            CompleteStoryData.getStoryNode("first_awakening") ?: SimpleStoryNode(
                id = "fallback",
                title = "初始化",
                content = "正在加载故事内容...",
                choices = emptyList()
            )
        )
    }
    var dialogueHistory by remember { mutableStateOf(listOf<DialogueEntry>()) }
    var isLoading by remember { mutableStateOf(false) }
    var gameMessage by remember { mutableStateOf("欢迎来到时间囚笼！第${gameState.currentLoop}次循环开始。") }
    var showControlMenu by remember { mutableStateOf(false) }
    var showDialogueHistory by remember { mutableStateOf(false) }
    
    // 检查游戏结束条件
    LaunchedEffect(gameState.health) {
        if (gameState.health <= 0) {
            currentNode = CompleteStoryData.getStoryNode("game_over_failure") ?: currentNode
            gameMessage = "健康值耗尽...循环重置"
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .statusBarsPadding()
    ) {
        // 顶部固定区域：标题和快捷按钮
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            // 左侧：游戏标题
            Column {
                Text(
                    text = "🌙 时间囚笼",
                    fontSize = 20.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color(0xFF00DDFF)
                )
                Text(
                    text = "循环 ${gameState.currentLoop} - 第 ${gameState.currentDay} 天",
                    fontSize = 12.sp,
                    color = Color(0xFF88FF88)
                )
            }
            
            // 右侧：快捷按钮
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                // 设置按钮
                IconButton(
                    onClick = { showControlMenu = true },
                    modifier = Modifier
                        .size(40.dp)
                        .background(
                            Color(0xFF003366),
                            shape = CircleShape
                        )
                ) {
                    Text(
                        text = "⚙️",
                        fontSize = 18.sp,
                        color = Color(0xFF00DDFF)
                    )
                }
                
                // AI协助按钮
                IconButton(
                    onClick = { /* AI 功能 */ },
                    modifier = Modifier
                        .size(40.dp)
                        .background(
                            Color(0xFF003366),
                            shape = CircleShape
                        )
                ) {
                    Text(
                        text = "🤖",
                        fontSize = 18.sp,
                        color = Color(0xFF00DDFF)
                    )
                }
            }
        }
        
        // 主要内容区域 - 可滚动
        LazyColumn(
            modifier = Modifier
                .weight(1f) // 占用剩余空间
                .padding(horizontal = 12.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp)
        ) {
            // 游戏状态栏
            item {
                TerminalWindow(
                    title = "状态",
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        verticalArrangement = Arrangement.spacedBy(8.dp)
                    ) {
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween
                        ) {
                            Column {
                                Text(
                                    text = "阶段: ${getGamePhase(gameState.currentDay)}",
                                    style = CyberTextStyles.Caption,
                                    color = Color(0xFF88FF88)
                                )
                                Text(
                                    text = "记忆保持: ${getMemoryRetention(gameState.currentLoop)}%",
                                    style = CyberTextStyles.Caption,
                                    color = Color(0xFFFFAA00)
                                )
                            }
                            
                            // 天气信息（居中）
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text(
                                    text = "天气状况",
                                    style = CyberTextStyles.Caption,
                                    color = Color(0xFFAAAA88)
                                )
                                Text(
                                    text = gameState.weather.displayName,
                                    style = CyberTextStyles.DataDisplay,
                                    color = getWeatherColor(gameState.weather)
                                )
                                Text(
                                    text = gameState.weather.description,
                                    style = CyberTextStyles.Caption,
                                    color = getWeatherColor(gameState.weather),
                                    fontSize = 10.sp
                                )
                            }
                            
                            Column(horizontalAlignment = Alignment.End) {
                                Text(
                                    text = "发现: ${gameState.exploredLocations.size}",
                                    style = CyberTextStyles.Caption,
                                    color = Color(0xFF88AAFF)
                                )
                                Text(
                                    text = "秘密: ${gameState.unlockedSecrets.size}",
                                    style = CyberTextStyles.Caption,
                                    color = Color(0xFFAA88FF)
                                )
                            }
                        }
                        
                        CyberDivider()
                        
                        // 宇航员状态指示器
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceEvenly
                        ) {
                            // 健康状态
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text("健康", color = Color(0xFFAAAA88), fontSize = 12.sp)
                                LinearProgressIndicator(
                                    progress = { gameState.health.toFloat() / gameState.maxHealth },
                                    modifier = Modifier.width(60.dp),
                                    color = if (gameState.health > 50) Color(0xFF00FF88) else Color(0xFFFF4444)
                                )
                                Text("${gameState.health}/${gameState.maxHealth}", color = Color(0xFF00FF88), fontSize = 10.sp)
                            }
                            
                            // 体力状态
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text("体力", color = Color(0xFFAAAA88), fontSize = 12.sp)
                                LinearProgressIndicator(
                                    progress = { gameState.stamina.toFloat() / gameState.maxStamina },
                                    modifier = Modifier.width(60.dp),
                                    color = if (gameState.stamina > 25) Color(0xFF00AAFF) else Color(0xFFFF4444)
                                )
                                Text("${gameState.stamina}/${gameState.maxStamina}", color = Color(0xFF00AAFF), fontSize = 10.sp)
                            }
                            
                            // 发现状态
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text("发现", color = Color(0xFFAAAA88), fontSize = 12.sp)
                                Text("${gameState.exploredLocations.size}/10", color = Color(0xFF88AAFF), fontSize = 14.sp)
                            }
                            
                            // 秘密状态
                            Column(horizontalAlignment = Alignment.CenterHorizontally) {
                                Text("秘密", color = Color(0xFFAAAA88), fontSize = 12.sp)
                                Text("${gameState.unlockedSecrets.size}/8", color = Color(0xFFAA88FF), fontSize = 14.sp)
                            }
                        }
                    }
                }
            }
            
            // 故事内容区域 - 只显示故事文本，选择按钮移到底部
            item {
                TerminalWindow(
                    title = "📖 ${currentNode.title}",
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(
                        modifier = Modifier.fillMaxWidth()
                    ) {
                        // 故事文本
                        Text(
                            text = currentNode.content,
                            style = CyberTextStyles.Terminal.copy(fontSize = 14.sp),
                            color = Color(0xFF88FF88),
                            modifier = Modifier.padding(bottom = 16.dp)
                        )
                        
                        // 测试信息
                        Text(
                            text = "测试: 节点ID=${currentNode.id}, 内容长度=${currentNode.content.length}, 选择数=${currentNode.choices.size}",
                            style = CyberTextStyles.Caption,
                            color = Color(0xFF666666),
                            modifier = Modifier.padding(bottom = 8.dp),
                            fontSize = 10.sp
                        )
                    }
                }
            }
        }
        
        // 底部固定操作区 - 选择按钮
        if (currentNode.choices.isNotEmpty()) {
            Surface(
                modifier = Modifier.fillMaxWidth(),
                color = Color(0xFF0A0A0A),
                shadowElevation = 8.dp
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(12.dp),
                    verticalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    CyberDivider()
                    
                    Text(
                        text = "选择你的行动:",
                        style = CyberTextStyles.Caption,
                        color = Color(0xFFAAAA88),
                        modifier = Modifier.padding(bottom = 4.dp)
                    )
                    
                    currentNode.choices.forEachIndexed { index, choice ->
                        NeonButton(
                            onClick = {
                                // 简化的选择处理
                                val nextNode = CompleteStoryData.getStoryNode(choice.nextNodeId)
                                if (nextNode != null) {
                                    currentNode = nextNode
                                    gameMessage = "你选择了：${choice.text}"
                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = 2.dp)
                        ) {
                            Text("${index + 1}. ${choice.text}")
                        }
                    }
                }
            }
        }
    }
    
    // 游戏控制菜单弹窗
    GameControlMenu(
        isVisible = showControlMenu,
        onDismiss = { showControlMenu = false },
        onSaveGame = { /* 暂时简化 */ },
        onLoadGame = { /* 暂时简化 */ },
        onNewLoop = {
            // 重新开始游戏
            gameState = GameState(currentLoop = gameState.currentLoop + 1)
            currentNode = CompleteStoryData.getStoryNode("first_awakening") ?: currentNode
            dialogueHistory = emptyList()
            gameMessage = "第${gameState.currentLoop}次循环开始！"
        },
        onAiAssist = { /* 暂时简化 */ },
        onShowHistory = { /* 暂时简化 */ },
        onSettings = { /* 暂时简化 */ }
    )
}

// 辅助函数移到文件外部
fun getGamePhase(day: Int): String {
    return when {
        day <= 3 -> "探索期"
        day <= 7 -> "适应期"
        day <= 14 -> "危机期"
        else -> "未知"
    }
}

fun getMemoryRetention(loop: Int): Int {
    return (50 + loop * 5).coerceAtMost(100)
}

fun getWeatherColor(weatherType: WeatherType): Color {
    return when (weatherType) {
        WeatherType.CLEAR -> Color(0xFF00FF88)
        WeatherType.LIGHT_RAIN -> Color(0xFF00AAFF)
        WeatherType.HEAVY_RAIN -> Color(0xFF0088CC)
        WeatherType.ACID_RAIN -> Color(0xFFFF4444)
        WeatherType.CYBER_STORM -> Color(0xFFAA00FF)
        WeatherType.SOLAR_FLARE -> Color(0xFFFF8800)
    }
}