import React, { useRef, useEffect, useState } from 'react';
import { Play, RotateCcw } from 'lucide-react';
import { useTranslation } from 'react-i18next';

interface GameState {
    isPlaying: boolean;
    isGameOver: boolean;
    score: number;
    lives: number;
}

const BreakoutGame: React.FC = () => {
    const { t } = useTranslation();
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const [gameState, setGameState] = useState<GameState>({
        isPlaying: false,
        isGameOver: false,
        score: 0,
        lives: 3
    });

    // Game constants
    const PADDLE_HEIGHT = 10;
    const PADDLE_WIDTH = 75;
    const BALL_RADIUS = 6;
    const BRICK_ROW_COUNT = 5;

    const BRICK_PADDING = 10;
    const BRICK_OFFSET_TOP = 30;
    const BRICK_OFFSET_LEFT = 30;
    const BRICK_HEIGHT = 20;

    // Refs to hold mutable game state without triggering re-renders
    const gameRef = useRef({
        x: 0,
        y: 0,
        dx: 4,
        dy: -4,
        paddleX: 0,
        bricks: [] as { x: number; y: number; status: number }[],
        animationId: 0,
        score: 0,
        rightPressed: false,
        leftPressed: false
    });

    const initGame = (canvas: HTMLCanvasElement) => {
        const { width, height } = canvas;
        const state = gameRef.current;

        state.x = width / 2;
        state.y = height - 30;
        state.dx = 4; // Speed
        state.dy = -4;
        state.paddleX = (width - PADDLE_WIDTH) / 2;
        state.score = 0;

        // Initialize bricks
        let actualCols = Math.floor((width - 2 * BRICK_OFFSET_LEFT) / (70 + BRICK_PADDING)); // Approx brick width 70
        if (actualCols < 1) actualCols = 1;

        const totalPadding = (actualCols - 1) * BRICK_PADDING;
        const availableWidth = width - 2 * BRICK_OFFSET_LEFT - totalPadding;
        const brickWidth = availableWidth / actualCols;

        state.bricks = [];
        for (let c = 0; c < actualCols; c++) {
            for (let r = 0; r < BRICK_ROW_COUNT; r++) {
                // Determine brick color/value? For now just status=1
                state.bricks.push({
                    x: (c * (brickWidth + BRICK_PADDING)) + BRICK_OFFSET_LEFT,
                    y: (r * (BRICK_HEIGHT + BRICK_PADDING)) + BRICK_OFFSET_TOP,
                    status: 1
                });
            }
        }

        return { brickWidth, actualCols };
    };

    useEffect(() => {
        const canvas = canvasRef.current;
        if (!canvas) return;

        const ctx = canvas.getContext('2d');
        if (!ctx) return;

        const drawBall = () => {
            ctx.beginPath();
            ctx.arc(gameRef.current.x, gameRef.current.y, BALL_RADIUS, 0, Math.PI * 2);
            ctx.fillStyle = '#64FFDA';
            ctx.fill();
            ctx.closePath();

            // Add glow
            ctx.shadowBlur = 10;
            ctx.shadowColor = "#64FFDA";
        };

        const drawPaddle = () => {
            ctx.beginPath();
            ctx.rect(gameRef.current.paddleX, canvas.height - PADDLE_HEIGHT - 10, PADDLE_WIDTH, PADDLE_HEIGHT);
            ctx.fillStyle = '#64FFDA';
            ctx.fill();
            ctx.closePath();
            ctx.shadowBlur = 0;
        };

        const drawBricks = (bWidth: number) => {
            gameRef.current.bricks.forEach(brick => {
                if (brick.status === 1) {
                    ctx.beginPath();
                    ctx.rect(brick.x, brick.y, bWidth, BRICK_HEIGHT);
                    ctx.fillStyle = 'rgba(100, 255, 218, 0.6)'; // Transparent teal
                    ctx.fill();
                    ctx.closePath();
                }
            });
        };

        const collisionDetection = (bWidth: number) => {
            const state = gameRef.current;
            state.bricks.forEach(brick => {
                if (brick.status === 1) {
                    if (state.x > brick.x && state.x < brick.x + bWidth && state.y > brick.y && state.y < brick.y + BRICK_HEIGHT) {
                        state.dy = -state.dy;
                        brick.status = 0;
                        state.score++;
                        setGameState(prev => ({ ...prev, score: state.score }));

                        // Check win (simple)
                        if (state.score === state.bricks.length) {
                            // Win logic, maybe reset bricks
                        }
                    }
                }
            });
        };

        const draw = (context: CanvasRenderingContext2D, cvs: HTMLCanvasElement, bWidth: number) => {
            context.clearRect(0, 0, cvs.width, cvs.height);

            drawBricks(bWidth);
            drawBall();
            drawPaddle();

            if (gameState.isPlaying && !gameState.isGameOver) {
                collisionDetection(bWidth);

                const state = gameRef.current;

                if (state.x + state.dx > cvs.width - BALL_RADIUS || state.x + state.dx < BALL_RADIUS) {
                    state.dx = -state.dx;
                }

                // Paddle movement logic
                if (state.rightPressed && state.paddleX < cvs.width - PADDLE_WIDTH) {
                    state.paddleX += 7;
                } else if (state.leftPressed && state.paddleX > 0) {
                    state.paddleX -= 7;
                }

                if (state.y + state.dy < BALL_RADIUS) {
                    state.dy = -state.dy;
                } else if (state.y + state.dy > cvs.height - BALL_RADIUS) {
                    if (state.x > state.paddleX && state.x < state.paddleX + PADDLE_WIDTH) {
                        // Paddle hit
                        // Add some English based on where it hit the paddle
                        const hitPoint = state.x - (state.paddleX + PADDLE_WIDTH / 2);
                        state.dx = hitPoint * 0.15; // Influence x speed
                        state.dy = -Math.abs(state.dy * 1.05); // Speed up slightly?
                        if (Math.abs(state.dx) < 2) state.dx = state.dx > 0 ? 2 : -2; // Min X speed
                    } else {
                        // Game Over
                        setGameState(prev => ({ ...prev, isGameOver: true, isPlaying: false }));
                        cancelAnimationFrame(state.animationId);
                        return;
                    }
                }

                state.x += state.dx;
                state.y += state.dy;

                state.animationId = requestAnimationFrame(() => draw(context, cvs, bWidth));
            } else if (!gameState.isPlaying) {
                // Just draw static if not playing
            }
        };

        // Set canvas size to match container
        const resizeCanvas = () => {
            const parent = canvas.parentElement;
            if (parent) {
                // Ensure non-zero dimensions to avoid division by zero or negative math
                canvas.width = parent.clientWidth || 300;
                canvas.height = parent.clientHeight || 300;

                if (!gameState.isPlaying) {
                    try {
                        const { brickWidth } = initGame(canvas);
                        draw(ctx, canvas, brickWidth);
                    } catch (e) {
                        console.error("Error drawing canvas:", e);
                    }
                }
            }
        };

        window.addEventListener('resize', resizeCanvas);
        resizeCanvas();

        // Keyboard event handlers
        const keyDownHandler = (e: KeyboardEvent) => {
            if (e.key === 'Right' || e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') {
                gameRef.current.rightPressed = true;
            } else if (e.key === 'Left' || e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') {
                gameRef.current.leftPressed = true;
            }
        };

        const keyUpHandler = (e: KeyboardEvent) => {
            if (e.key === 'Right' || e.key === 'ArrowRight' || e.key === 'd' || e.key === 'D') {
                gameRef.current.rightPressed = false;
            } else if (e.key === 'Left' || e.key === 'ArrowLeft' || e.key === 'a' || e.key === 'A') {
                gameRef.current.leftPressed = false;
            }
        };

        window.addEventListener('keydown', keyDownHandler);
        window.addEventListener('keyup', keyUpHandler);

        let { brickWidth } = initGame(canvas); // Initial draw

        // Initial static draw if not playing
        // Initial draw or start loop
        draw(ctx, canvas, brickWidth);

        return () => {
            window.removeEventListener('resize', resizeCanvas);
            window.removeEventListener('keydown', keyDownHandler);
            window.removeEventListener('keyup', keyUpHandler);
            cancelAnimationFrame(gameRef.current.animationId);
        };
    }, [gameState.isPlaying, gameState.isGameOver]); // Re-run effect when play state changes

    const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
        if (!gameState.isPlaying || gameState.isGameOver) return;
        const canvas = canvasRef.current;
        if (!canvas) return;

        const rect = canvas.getBoundingClientRect();
        const relativeX = e.clientX - rect.left;

        if (relativeX > 0 && relativeX < canvas.width) {
            gameRef.current.paddleX = relativeX - PADDLE_WIDTH / 2;
        }
    };

    // Also support touch
    const handleTouchMove = (e: React.TouchEvent<HTMLDivElement>) => {
        if (!gameState.isPlaying || gameState.isGameOver) return;
        const canvas = canvasRef.current;
        if (!canvas) return;

        const rect = canvas.getBoundingClientRect();
        const touch = e.touches[0];
        const relativeX = touch.clientX - rect.left;

        if (relativeX > 0 && relativeX < canvas.width) {
            gameRef.current.paddleX = relativeX - PADDLE_WIDTH / 2;
        }
    }

    const startGame = () => {
        const canvas = canvasRef.current;
        if (canvas) {
            initGame(canvas);
            setGameState({ isPlaying: true, isGameOver: false, score: 0, lives: 3 });
        }
    };

    return (
        <div
            className="w-full h-full relative group cursor-none"
            onMouseMove={handleMouseMove}
            onTouchMove={handleTouchMove}
        >
            <canvas
                ref={canvasRef}
                className="block w-full h-full bg-[#112240] rounded-2xl"
            />

            {/* Overlay UI */}
            {(!gameState.isPlaying || gameState.isGameOver) && (
                <div className="absolute inset-0 bg-[#0A192F]/80 backdrop-blur-sm flex flex-col items-center justify-center z-10 transition-all duration-300">
                    {/* Game Over State */}
                    {gameState.isGameOver ? (
                        <div className="text-center">
                            <h3 className="text-2xl font-bold text-white mb-2">{t('game.over')}</h3>
                            <p className="text-[#64FFDA] mb-4 text-xl">{t('game.score')}: {gameState.score}</p>
                            <button
                                onClick={startGame}
                                className="flex items-center gap-2 px-6 py-3 bg-[#64FFDA] text-[#0A192F] font-bold rounded-full hover:bg-[#64FFDA]/90 transition-all mx-auto cursor-pointer"
                            >
                                <RotateCcw size={20} />
                                {t('game.try_again')}
                            </button>
                        </div>
                    ) : (
                        /* Initial Start State - Matches original design */
                        <div className="w-full h-full flex flex-col justify-end p-8 relative">
                            {/* Play hint overlay in center */}
                            <div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-center group-hover:scale-110 transition-transform duration-300">
                                <button
                                    onClick={startGame}
                                    className="w-20 h-20 bg-[#64FFDA] rounded-full flex items-center justify-center shadow-[0_0_30px_rgba(100,255,218,0.3)] animate-pulse hover:animate-none"
                                >
                                    <Play size={32} className="text-[#0A192F] ml-1" fill="currentColor" />
                                </button>
                                <p className="text-[#64FFDA] text-sm mt-4 font-bold tracking-widest uppercase">{t('game.click')}</p>
                            </div>

                            {/* Statistic Card Style */}
                            <div className="bg-[#0A192F]/90 backdrop-blur border border-[#64FFDA]/30 p-6 rounded-xl w-full">
                                <div className="flex justify-between items-end">
                                    <div>
                                        <p className="text-slate-400 text-xs uppercase tracking-wider mb-1">{t('game.saved')}</p>
                                        <p className="text-2xl font-bold text-white">∞ <span className="text-[#64FFDA] text-sm font-normal">{t('game.hours')}</span></p>
                                    </div>
                                    <div className="text-[#64FFDA] font-mono text-xs border border-[#64FFDA] px-2 py-1 rounded">
                                        {t('game.level')}
                                    </div>
                                </div>
                            </div>
                        </div>
                    )}
                </div>
            )}

            {/* Stats Overlay Corner */}
            {gameState.isPlaying && (
                <div className="absolute top-4 right-4 text-[#64FFDA] font-mono font-bold text-lg select-none pointer-events-none">
                    {gameState.score}
                </div>
            )}
        </div>
    );
};

export default BreakoutGame;
