package com.dong.maxhap.demos.game

import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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 XiangqiScreen(onBack: () -> Unit) {
    val logic = remember { XiangqiLogic() }
    var gameState by remember { mutableStateOf(logic.initializeGame()) }
    
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp)
            .background(Color(0xFFDEB887)),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "🐘🐎 象棋",
                fontSize = 24.sp,
                fontWeight = FontWeight.Bold,
                color = Color(0xFF8B4513)
            )
            
            Text(
                text = when {
                    gameState.gameOver -> "游戏结束"
                    gameState.currentPlayer == ChessPieceColor.RED -> "红方行棋"
                    else -> "黑方行棋"
                },
                fontSize = 18.sp,
                fontWeight = FontWeight.Medium,
                color = when {
                    gameState.gameOver -> Color.Red
                    gameState.currentPlayer == ChessPieceColor.RED -> Color.Red
                    else -> Color.Black
                }
            )
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Box(
            modifier = Modifier
                .size(360.dp)
                .background(Color(0xFFDEB887))
                .clickable { 
                    gameState = logic.deselectPiece(gameState)
                }
        ) {
            ChessBoard(
                gameState = gameState,
                onSquareClick = { position ->
                    gameState = logic.selectPiece(gameState, position)
                }
            )
        }
        
        Spacer(modifier = Modifier.height(16.dp))
        
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Button(
                onClick = {
                    gameState = logic.restartGame()
                },
                colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF8B4513)),
                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 = when (gameState.winner) {
                    ChessPieceColor.RED -> "红方获胜! 🎉"
                    ChessPieceColor.BLACK -> "黑方获胜! 🎉"
                    null -> "游戏结束"
                },
                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• 吃掉对方将/帅即获胜\n• 遵循中国象棋规则",
            fontSize = 12.sp,
            color = Color.Gray,
            textAlign = TextAlign.Center,
            modifier = Modifier.fillMaxWidth()
        )
    }
}

@Composable
private fun ChessBoard(
    gameState: XiangqiGameState,
    onSquareClick: (Offset) -> Unit
) {
    val squareSize = 360.dp / XiangqiLogic.BOARD_WIDTH
    
    Canvas(modifier = Modifier.fillMaxSize()) {
        val canvasWidth = size.width
        val canvasHeight = size.height
        val cellWidth = canvasWidth / XiangqiLogic.BOARD_WIDTH
        val cellHeight = canvasHeight / XiangqiLogic.BOARD_HEIGHT
        
        drawChessBoardLines(cellWidth, cellHeight)
        drawPalaceLines(cellWidth, cellHeight)
        
        gameState.board.forEachIndexed { row, pieces ->
            pieces.forEachIndexed { col, piece ->
                if (piece != null) {
                    drawChessPiece(
                        piece = piece,
                        x = col * cellWidth + cellWidth / 2,
                        y = row * cellHeight + cellHeight / 2,
                        radius = cellWidth * 0.4f
                    )
                }
            }
        }
        
        gameState.selectedPiece?.let { pos ->
            drawSelectedIndicator(
                x = pos.x * cellWidth + cellWidth / 2,
                y = pos.y * cellHeight + cellHeight / 2,
                radius = cellWidth * 0.45f
            )
        }
    }
    
    Box(modifier = Modifier.fillMaxSize()) {
        for (row in 0 until XiangqiLogic.BOARD_HEIGHT) {
            for (col in 0 until XiangqiLogic.BOARD_WIDTH) {
                Box(
                    modifier = Modifier
                        .size(squareSize)
                        .offset(
                            x = (col * squareSize.value).dp,
                            y = (row * squareSize.value).dp
                        )
                        .clickable { 
                            onSquareClick(Offset(col.toFloat(), row.toFloat()))
                        }
                )
            }
        }
    }
}

private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawChessBoardLines(
    cellWidth: Float,
    cellHeight: Float
) {
    for (i in 0..XiangqiLogic.BOARD_WIDTH) {
        val x = i * cellWidth
        drawLine(
            color = Color.Black,
            start = Offset(x, 0f),
            end = Offset(x, size.height),
            strokeWidth = 2f
        )
    }
    
    for (i in 0..XiangqiLogic.BOARD_HEIGHT) {
        val y = i * cellHeight
        drawLine(
            color = Color.Black,
            start = Offset(0f, y),
            end = Offset(size.width, y),
            strokeWidth = 2f
        )
    }
}

private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawPalaceLines(
    cellWidth: Float,
    cellHeight: Float
) {
    drawLine(
        color = Color.Black,
        start = Offset(3 * cellWidth, 0 * cellHeight),
        end = Offset(5 * cellWidth, 2 * cellHeight),
        strokeWidth = 2f
    )
    drawLine(
        color = Color.Black,
        start = Offset(5 * cellWidth, 0 * cellHeight),
        end = Offset(3 * cellWidth, 2 * cellHeight),
        strokeWidth = 2f
    )
    
    drawLine(
        color = Color.Black,
        start = Offset(3 * cellWidth, 7 * cellHeight),
        end = Offset(5 * cellWidth, 9 * cellHeight),
        strokeWidth = 2f
    )
    drawLine(
        color = Color.Black,
        start = Offset(5 * cellWidth, 7 * cellHeight),
        end = Offset(3 * cellWidth, 9 * cellHeight),
        strokeWidth = 2f
    )
}

private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawChessPiece(
    piece: ChessPiece,
    x: Float,
    y: Float,
    radius: Float
) {
    drawCircle(
        color = when (piece.color) {
            ChessPieceColor.RED -> Color.Red
            ChessPieceColor.BLACK -> Color.Black
        },
        radius = radius,
        center = Offset(x, y)
    )
    
    drawCircle(
        color = Color.White,
        radius = radius - 2f,
        center = Offset(x, y),
        style = androidx.compose.ui.graphics.drawscope.Stroke(width = 2f)
    )
}

private fun androidx.compose.ui.graphics.drawscope.DrawScope.drawSelectedIndicator(
    x: Float,
    y: Float,
    radius: Float
) {
    drawCircle(
        color = Color.Blue,
        radius = radius,
        center = Offset(x, y),
        style = androidx.compose.ui.graphics.drawscope.Stroke(width = 3f)
    )
}