import React, { useEffect, useRef, useState } from "react";

import styles from "./FlappyCodey.module.css";

type GameState = "welcome" | "playing" | "game-over";

interface Bird {
  x: number;
  y: number;
  velocityY: number;
}

interface PipePair {
  x: number;
  topY: number;
  bottomY: number;
  passed: boolean;
}

interface World {
  bird: Bird;
  pipes: PipePair[];
  score: number;
  pipeSpeed: number;
}

interface GameImages {
  background: HTMLImageElement;
  bird: HTMLImageElement;
  topPipe: HTMLImageElement;
  bottomPipe: HTMLImageElement;
}

interface Rectangle {
  x: number;
  y: number;
  width: number;
  height: number;
}

const gameWidth = 360;
const gameHeight = 640;

const birdWidth = 68;
const birdHeight = 68;
const birdStartX = gameWidth / 8;
const birdStartY = gameHeight / 2;

const flapStrength = -6;
const gravity = 0.4;

const pipeWidth = 64;
const pipeHeight = 512;

const basePipeSpeed = -2;
const maxPipeSpeed = -4.5;
const speedIncreasePerPoint = 0.05;

const startingOpeningSpace = gameHeight / 4;
const minOpeningSpace = 110;
const gapReductionPerPoint = 2;

const minPipeDelay = 1200;
const maxPipeDelay = 1800;

const highScoreKey = "flappy-codey-high-score";

const assetBase = "/images/games/flappy-codey";

export function FlappyCodey() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);
  const animationFrameRef = useRef<number | null>(null);
  const actionRef = useRef<() => void>(() => undefined);

  const [gameState, setGameState] = useState<GameState>("welcome");
  const [score, setScore] = useState(0);
  const [highScore, setHighScore] = useState(0);
  const [message, setMessage] = useState(
    "Press Space, ↑, X, click, or tap to play."
  );

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

    if (canvas == null) {
      return;
    }

    const context = canvas.getContext("2d");

    if (context == null) {
      return;
    }

    const renderingContext = context;

    let mounted = true;
    let images: GameImages | null = null;
    let world = createWorld();
    let currentState: GameState = "welcome";
    let savedHighScore = readStoredHighScore();
    let lastTimestamp = 0;
    let lastPipeTimestamp = 0;
    let nextPipeDelay = randomPipeDelay();

    setHighScore(savedHighScore);

    function setState(nextState: GameState) {
      currentState = nextState;
      setGameState(nextState);
    }

    function updateScore() {
      setScore(Math.floor(world.score));
      setHighScore(savedHighScore);
    }

    function endGame() {
      setState("game-over");

      const finalScore = Math.floor(world.score);

      if (finalScore > savedHighScore) {
        savedHighScore = finalScore;
        window.localStorage.setItem(highScoreKey, String(savedHighScore));
      }

      updateScore();
      setMessage("Game over. Press Space, ↑, X, click, or tap to restart.");
    }

    function startGame() {
      world = createWorld();
      world.bird.velocityY = flapStrength;
      lastPipeTimestamp = window.performance.now();
      nextPipeDelay = randomPipeDelay();

      setState("playing");
      updateScore();
      setMessage("Keep Codey flying through the pipes.");
    }

    function flap() {
      if (currentState === "welcome" || currentState === "game-over") {
        startGame();
      } else {
        world.bird.velocityY = flapStrength;
      }
    }

    function handleKeyDown(event: KeyboardEvent) {
      if (
        event.key === " " ||
        event.key === "ArrowUp" ||
        event.key === "x" ||
        event.key === "X"
      ) {
        event.preventDefault();
        flap();
      }
    }

    function update(timestamp: number, deltaScale: number) {
      world.bird.velocityY += gravity * deltaScale;
      world.bird.y += world.bird.velocityY * deltaScale;

      if (world.bird.y < 0) {
        world.bird.y = 0;
        world.bird.velocityY = 0;
      }

      if (world.bird.y + birdHeight >= gameHeight) {
        world.bird.y = gameHeight - birdHeight;
        endGame();
        return;
      }

      if (timestamp - lastPipeTimestamp >= nextPipeDelay) {
        world.pipes.push(createPipePair(world.score));
        lastPipeTimestamp = timestamp;
        nextPipeDelay = randomPipeDelay();
      }

      const birdHitbox = {
        x: world.bird.x + 14,
        y: world.bird.y + 12,
        width: birdWidth - 28,
        height: birdHeight - 24,
      };

      world.pipes.forEach((pipe) => {
        pipe.x += world.pipeSpeed * deltaScale;

        if (!pipe.passed && world.bird.x > pipe.x + pipeWidth) {
          pipe.passed = true;
          world.score += 1;
          world.pipeSpeed = Math.max(
            maxPipeSpeed,
            basePipeSpeed - world.score * speedIncreasePerPoint
          );
          updateScore();
        }

        const topPipe = {
          x: pipe.x,
          y: pipe.topY,
          width: pipeWidth,
          height: pipeHeight,
        };

        const bottomPipe = {
          x: pipe.x,
          y: pipe.bottomY,
          width: pipeWidth,
          height: pipeHeight,
        };

        if (
          rectanglesOverlap(birdHitbox, topPipe) ||
          rectanglesOverlap(birdHitbox, bottomPipe)
        ) {
          endGame();
        }
      });

      world.pipes = world.pipes.filter((pipe) => pipe.x + pipeWidth >= 0);
    }

    function loop(timestamp: number) {
      if (!mounted || images == null) {
        return;
      }

      if (lastTimestamp === 0) {
        lastTimestamp = timestamp;
      }

      const deltaScale = Math.min((timestamp - lastTimestamp) / 16.67, 2);
      lastTimestamp = timestamp;

      if (currentState === "playing") {
        update(timestamp, deltaScale);
      }

      draw(
        renderingContext,
        images,
        world,
        currentState,
        savedHighScore,
        timestamp
      );

      animationFrameRef.current = window.requestAnimationFrame(loop);
    }

    actionRef.current = flap;
    window.addEventListener("keydown", handleKeyDown);

    void loadImages().then((loadedImages) => {
      if (!mounted) {
        return;
      }

      images = loadedImages;
      animationFrameRef.current = window.requestAnimationFrame(loop);
    });

    return () => {
      mounted = false;
      window.removeEventListener("keydown", handleKeyDown);

      if (animationFrameRef.current != null) {
        window.cancelAnimationFrame(animationFrameRef.current);
      }
    };
  }, []);

  return (
    <section className={styles.game}>
      <div className={styles.canvasFrame}>
        <canvas
          ref={canvasRef}
          className={styles.canvas}
          width={gameWidth}
          height={gameHeight}
          aria-label="Flappy Codey game canvas"
          onPointerDown={() => actionRef.current()}
        />
      </div>
      <aside className={styles.panel}>
        <p className={styles.score}>Score: {score}</p>
        <p className={styles.score}>High Score: {highScore}</p>
        <p className={styles.status}>{message}</p>
        <button className={styles.button} onClick={() => actionRef.current()}>
          {gameState === "playing" ? "Flap" : "Start"}
        </button>
      </aside>
    </section>
  );
}

function createWorld(): World {
  return {
    bird: {
      x: birdStartX,
      y: birdStartY,
      velocityY: 0,
    },
    pipes: [],
    score: 0,
    pipeSpeed: basePipeSpeed,
  };
}

function createPipePair(score: number): PipePair {
  const topY = -pipeHeight / 4 - Math.random() * (pipeHeight / 2);
  const openingSpace = Math.max(
    minOpeningSpace,
    startingOpeningSpace - Math.floor(score) * gapReductionPerPoint
  );

  return {
    x: gameWidth,
    topY,
    bottomY: topY + pipeHeight + openingSpace,
    passed: false,
  };
}

function randomPipeDelay() {
  return Math.floor(
    minPipeDelay + Math.random() * (maxPipeDelay - minPipeDelay)
  );
}

function rectanglesOverlap(first: Rectangle, second: Rectangle) {
  return (
    first.x < second.x + second.width &&
    first.x + first.width > second.x &&
    first.y < second.y + second.height &&
    first.y + first.height > second.y
  );
}

function readStoredHighScore() {
  const storedScore = window.localStorage.getItem(highScoreKey);
  const parsedScore = Number.parseInt(storedScore ?? "0", 10);

  return Number.isNaN(parsedScore) ? 0 : parsedScore;
}

function loadImages() {
  return Promise.all([
    loadImage(`${assetBase}/flappybirdbg.png`),
    loadImage(`${assetBase}/flappybird.png`),
    loadImage(`${assetBase}/toppipe.png`),
    loadImage(`${assetBase}/bottompipe.png`),
  ]).then(([background, bird, topPipe, bottomPipe]) => ({
    background,
    bird,
    topPipe,
    bottomPipe,
  }));
}

function loadImage(source: string) {
  return new Promise<HTMLImageElement>((resolve, reject) => {
    const image = new Image();

    image.onload = () => resolve(image);
    image.onerror = () => reject(new Error(`Could not load ${source}`));
    image.src = source;
  });
}

function draw(
  context: CanvasRenderingContext2D,
  images: GameImages,
  world: World,
  gameState: GameState,
  highScore: number,
  timestamp: number
) {
  context.clearRect(0, 0, gameWidth, gameHeight);
  context.drawImage(images.background, 0, 0, gameWidth, gameHeight);

  if (gameState === "welcome") {
    drawCenteredText(context, "FLAPPY CODEY", 50, gameHeight / 2 - 130);

    const bobOffset = Math.sin(timestamp / 250) * 8;

    context.drawImage(
      images.bird,
      gameWidth / 2 - birdWidth / 2,
      gameHeight / 2 - 35 - birdHeight / 2 + bobOffset,
      birdWidth,
      birdHeight
    );

    drawCenteredText(
      context,
      "PRESS SPACE, ↑, X, CLICK, OR TAP",
      17,
      gameHeight / 2 + 55
    );

    drawCenteredText(
      context,
      `HIGH SCORE: ${highScore}`,
      24,
      gameHeight / 2 + 100
    );

    return;
  }

  world.pipes.forEach((pipe) => {
    context.drawImage(images.topPipe, pipe.x, pipe.topY, pipeWidth, pipeHeight);

    context.drawImage(
      images.bottomPipe,
      pipe.x,
      pipe.bottomY,
      pipeWidth,
      pipeHeight
    );
  });

  context.drawImage(
    images.bird,
    world.bird.x,
    world.bird.y,
    birdWidth,
    birdHeight
  );

  drawCenteredText(context, String(Math.floor(world.score)), 35, 32);

  if (gameState === "game-over") {
    drawCenteredText(context, "GAME OVER!", 50, gameHeight / 2 - 100);
    drawCenteredText(
      context,
      `SCORE: ${Math.floor(world.score)}`,
      32,
      gameHeight / 2 - 25
    );
    drawCenteredText(
      context,
      `HIGH SCORE: ${highScore}`,
      24,
      gameHeight / 2 + 20
    );
    drawCenteredText(
      context,
      "PRESS SPACE, ↑, X, CLICK, OR TAP AGAIN",
      14,
      gameHeight / 2 + 85
    );
  }
}

function drawCenteredText(
  context: CanvasRenderingContext2D,
  text: string,
  size: number,
  centerY: number
) {
  context.font = `700 ${size}px Poppins, sans-serif`;
  context.textAlign = "center";
  context.textBaseline = "middle";

  context.fillStyle = "black";
  context.fillText(text, gameWidth / 2 + 2, centerY + 2);

  context.fillStyle = "white";
  context.fillText(text, gameWidth / 2, centerY);
}
