package com.dong.maxhap.demos.game

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

@Composable
internal fun SnakeGameScreen(onBack: () -> Unit) {
    val logic = remember { SnakeGameLogic() }
    var gameState by remember { mutableStateOf(logic.initializeGame()) }
    val coroutineScope = rememberCoroutineScope()
    
    // 游戏循环
    LaunchedEffect(gameState.gameOver, gameState.gamePaused) {
        if (!gameState.gameOver && !gameState.gamePaused) {
            while (true) {
                delay(200) // 控制游戏速度
                gameState = logic.moveSnake(gameState)
                if (logic.isGameOver(gameState)) {
                    gameState = gameState.copy(gameOver = true)
                    break
                }
            }
        }
    }
    
    // 处理按键输入
    fun handleDirectionChange(direction: Offset) {
        if (!gameState.gameOver) {
            gameState = logic.changeDirection(gameState, direction)
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .background(Color.Black),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 标题和分数
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "🐍 贪吃蛇",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = Color.White
            )
            
            Text(
                text = "得分: ${gameState.score}",
                fontSize = 18.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Yellow
            )
        }
        
        Spacer(modifier = Height(16.dp))
        
        // 游戏区域
        Box(
            modifier = Modifier
                .size(
                    (SnakeGameLogic.GRID_WIDTH * SnakeGameLogic.CELL_SIZE.toInt()).dp,
                    (SnakeGameLogic.GRID_HEIGHT * SnakeGameLogic.CELL_SIZE.toInt()).dp
                )
                .background(Color.DarkGray)
                .pointerInput(Unit) {
                    detectTapGestures { offset ->
                        // 简单的触摸控制 - 根据点击位置改变方向
                        val centerX = size.width / 2
                        val centerY = size.height / 2
                        
                        val direction = when {
                            offset.x < centerX && abs(offset.x - centerX) > abs(offset.y - centerY) -> 
                                Offset(-1f, 0f) // 左
                            offset.x > centerX && abs(offset.x - centerX) > abs(offset.y - centerY) -> 
                                Offset(1f, 0f)  // 右
                            offset.y < centerY -> 
                                Offset(0f, -1f) // 上
                            else -> 
                                Offset(0f, 1f)  // 下
                        }
                        handleDirectionChange(direction)
                    }
                }
        ) {
            Canvas(modifier = Modifier.fillMaxSize()) {
                // 绘制食物
                drawCircle(
                    color = Color.Red,
                    radius = SnakeGameLogic.CELL_SIZE / 2,
                    center = Offset(
                        gameState.food.x * SnakeGameLogic.CELL_SIZE + SnakeGameLogic.CELL_SIZE / 2f,
                        gameState.food.y * SnakeGameLogic.CELL_SIZE + SnakeGameLogic.CELL_SIZE / 2f
                    )
                )
                
                // 绘制蛇身
                gameState.snake.forEachIndexed { index, segment ->
                    val color = if (index == 0) Color.Green else Color(0xFF90EE90)
                    drawRect(
                        color = color,
                        topLeft = Offset(
                            segment.x * SnakeGameLogic.CELL_SIZE,
                            segment.y * SnakeGameLogic.CELL_SIZE
                        ),
                        size = androidx.compose.ui.geometry.Size(
                            SnakeGameLogic.CELL_SIZE,
                            SnakeGameLogic.CELL_SIZE
                        )
                    )
                }
            }
        }
        
        Spacer(modifier = Height(16.dp))
        
        // 控制按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            DirectionButton("↑") { handleDirectionChange(Offset(0f, -1f)) }
            DirectionButton("↓") { handleDirectionChange(Offset(0f, 1f)) }
            DirectionButton("←") { handleDirectionChange(Offset(-1f, 0f)) }
            DirectionButton("→") { handleDirectionChange(Offset(1f, 0f)) }
        }
        
        Spacer(modifier = Height(16.dp))
        
        // 操作按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Button(
                onClick = {
                    gameState = if (gameState.gamePaused) {
                        logic.togglePause(gameState)
                    } else {
                        logic.restartGame()
                    }
                },
                colors = ButtonDefaults.buttonColors(
                    backgroundColor = if (gameState.gamePaused) Color.Green else Color(0xFF8F7A66)
                ),
                modifier = Modifier.weight(1f)
            ) {
                Text(
                    text = if (gameState.gamePaused) "继续" else "重新开始",
                    color = Color.White
                )
            }
            
            Spacer(modifier = Width(16.dp))
            
            Button(
                onClick = onBack,
                colors = ButtonDefaults.buttonColors(backgroundColor = Color.Gray),
                modifier = Modifier.weight(1f)
            ) {
                Text("返回", color = Color.White)
            }
        }
        
        // 游戏状态提示
        if (gameState.gameOver) {
            Spacer(modifier = Height(16.dp))
            Text(
                text = "游戏结束! 😢",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Red,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        } else if (gameState.gamePaused) {
            Spacer(modifier = Height(16.dp))
            Text(
                text = "游戏暂停 ⏸️",
                fontSize = 18.sp,
                fontWeight = FontWeight.Medium,
                color = Color.Yellow,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        }
        
        Spacer(modifier = Height(16.dp))
        
        // 操作说明
        Text(
            text = "操作说明:\n• 点击屏幕或使用方向键控制蛇的移动\n• 吃到红色食物可以增长身体并获得分数\n• 避免撞到自己或边界\n• 按暂停键可以暂停/继续游戏",
            fontSize = 12.sp,
            color = Color.Gray,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
private fun DirectionButton(text: String, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        modifier = Modifier.size(60.dp),
        colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF4A4A4A)),
        shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp)
    ) {
        Text(
            text = text,
            fontSize = 20.sp,
            color = Color.White,
            fontWeight = FontWeight.Bold
        )
    }
}

// 注意：这里可能需要导入或定义Height和Width，如果不存在的话
// 如果编译报错，可以替换为Modifier.height()和Modifier.width()
private fun Height(dp: androidx.compose.ui.unit.Dp) = Modifier.height(dp)
private fun Width(dp: androidx.compose.ui.unit.Dp) = Modifier.width(dp)

private fun abs(value: Float): Float = if (value < 0) -value else value