package com.dong.maxhap.demos.game

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
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.draw.clip
import androidx.compose.ui.graphics.Color
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

@Composable
internal fun Game2048Screen(onBack: () -> Unit) {
    val logic = remember { Game2048Logic() }
    var gameState by remember { 
        mutableStateOf(
            Game2048State(
                grid = logic.doInitGrid(),
                score = 0,
                gameOver = false,
                won = false
            )
        ) 
    }
    
    fun handleMove(moveFunction: (List<List<Int>>) -> Pair<List<List<Int>>, Int>) {
        if (gameState.gameOver) return
        
        val (newGrid, scoreGain) = moveFunction(gameState.grid)
        if (newGrid != gameState.grid) {
            val updatedGrid = logic.addRandomTile(newGrid)
            val newScore = gameState.score + scoreGain
            val won = logic.checkWin(updatedGrid)
            val gameOver = logic.checkGameOver(updatedGrid)
            
            gameState = Game2048State(
                grid = updatedGrid,
                score = newScore,
                gameOver = gameOver,
                won = won
            )
        }
    }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 标题和分数栏
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "🎮 2048",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold
            )
            
            Column(
                horizontalAlignment = Alignment.End
            ) {
                Text(
                    text = "得分: ${gameState.score}",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Medium
                )
                if (gameState.won) {
                    Text(
                        text = "🎉 恭喜获胜!",
                        color = Color.Green,
                        fontSize = 14.sp
                    )
                }
            }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 游戏网格
        Box(
            modifier = Modifier
                .size(320.dp)
                .background(Color(0xFFBBADA0), RoundedCornerShape(8.dp))
                .padding(8.dp)
        ) {
            GameGrid(grid = gameState.grid)
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 控制按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceEvenly
        ) {
            DirectionButton("↑") { handleMove { logic.moveUp(it) } }
            DirectionButton("↓") { handleMove { logic.moveDown(it) } }
            DirectionButton("←") { handleMove { logic.moveLeft(it) } }
            DirectionButton("→") { handleMove { logic.moveRight(it) } }
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 操作按钮
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Button(
                onClick = {
                    gameState = Game2048State(
                        grid = logic.doInitGrid(),
                        score = 0,
                        gameOver = false,
                        won = false
                    )
                },
                colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF8F7A66)),
                modifier = Modifier.weight(1f)
            ) {
                Text("重新开始", color = Color.White)
            }
            
            Spacer(modifier = 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 = Modifier.height(16.dp))
            Text(
                text = "游戏结束! 😢",
                fontSize = 20.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Red,
                textAlign = TextAlign.Center,
                modifier = Modifier.fillMaxWidth()
            )
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        // 操作说明
        Text(
            text = "操作说明:\n• 点击方向键移动方块\n• 相同数字的方块相遇时会合并\n• 达到2048即获胜\n• 无法移动时游戏结束",
            fontSize = 12.sp,
            color = Color.Gray,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
private fun GameGrid(grid: List<List<Int>>) {
    Column(
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        grid.forEach { row ->
            Row(
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                row.forEach { value ->
                    GameTile(value = value)
                }
            }
        }
    }
}

@Composable
private fun GameTile(value: Int) {
    val (backgroundColor, textColor) = getTileColors(value)
    
    Box(
        modifier = Modifier
            .size(70.dp)
            .clip(RoundedCornerShape(4.dp))
            .background(backgroundColor)
            .border(1.dp, Color(0xFFCDC1B4), RoundedCornerShape(4.dp)),
        contentAlignment = Alignment.Center
    ) {
        if (value != 0) {
            Text(
                text = value.toString(),
                fontSize = when {
                    value < 10 -> 28.sp
                    value < 100 -> 24.sp
                    value < 1000 -> 20.sp
                    else -> 16.sp
                },
                fontWeight = FontWeight.Bold,
                color = textColor
            )
        }
    }
}

private fun getTileColors(value: Int): Pair<Color, Color> {
    return when (value) {
        0 -> Color(0xFFCDC1B4) to Color.Transparent
        2 -> Color(0xFFEEE4DA) to Color(0xFF776E65)
        4 -> Color(0xFFEDE0C8) to Color(0xFF776E65)
        8 -> Color(0xFFF2B179) to Color.White
        16 -> Color(0xFFF59563) to Color.White
        32 -> Color(0xFFF67C5F) to Color.White
        64 -> Color(0xFFF65E3B) to Color.White
        128 -> Color(0xFFEDCF72) to Color.White
        256 -> Color(0xFFEDCC61) to Color.White
        512 -> Color(0xFFEDC850) to Color.White
        1024 -> Color(0xFFEDC53F) to Color.White
        2048 -> Color(0xFFEDC22E) to Color.White
        else -> Color(0xFF3C3A32) to Color.White
    }
}

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