package se.urmo.game.state;

import lombok.Getter;
import se.urmo.game.main.GamePanel;
import se.urmo.game.main.GameStateManager;
import se.urmo.game.main.HighScoreManager;
import se.urmo.game.util.GameFonts;
import se.urmo.game.util.GameStateType;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

public class GameOverState implements GameState {
    private final GameStateManager gsm;
    private int finalScore = 0;
    private int finalLevel = 0;
    @Getter
    private final HighScoreManager highScores; // optional

    private boolean saved = false;
    private long startMs = System.currentTimeMillis();

    public GameOverState(GameStateManager gsm, HighScoreManager highScores) {
        this.gsm = gsm;
        this.highScores = highScores;
    }

    @Override
    public void update() {
        if (!saved) {
            if (highScores != null) highScores.submit(finalScore);
            saved = true;
        }
        // could auto-return to menu after N seconds if you like
    }

    @Override
    public void render(Graphics2D g) {
        // Clear / dim background
        g.setColor(new Color(0,0,0,200));
        g.fillRect(0,0, GamePanel.SCREEN_WIDTH, GamePanel.SCREEN_HEIGHT);

        // Title
        g.setColor(Color.RED);
        g.setFont(GameFonts.arcade(32f));
        drawCentered(g, "GAME OVER", GamePanel.SCREEN_HEIGHT/2 - 40);

        // Stats
        g.setColor(Color.WHITE);
        g.setFont(GameFonts.arcade(18f));
        drawCentered(g, "SCORE: " + finalScore, GamePanel.SCREEN_HEIGHT/2);
        drawCentered(g, "LEVEL: " + finalLevel, GamePanel.SCREEN_HEIGHT/2 + 24);

        // Prompt
        g.setFont(GameFonts.arcade(12f));
        drawCentered(g, "Press..", GamePanel.SCREEN_HEIGHT/2 + 64);
        drawCentered(g, "ENTER to restart  •  ESC for menu", GamePanel.SCREEN_HEIGHT/2 + 78);
    }

    private void drawCentered(Graphics2D g, String text, int y) {
        var fm = g.getFontMetrics();
        int x = (GamePanel.SCREEN_WIDTH - fm.stringWidth(text)) / 2;
        g.drawString(text, x, y);
    }

    @Override
    public void keyPressed(KeyEvent e) {
        switch (e.getKeyCode()) {
            case KeyEvent.VK_ENTER -> restartNewGame();
            case KeyEvent.VK_ESCAPE -> goToMenu();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    private void restartNewGame() {
        // Build a fresh PlayingState with everything reset
        gsm.setState(GameStateType.PLAYING);
    }

    private void goToMenu() {
//        MenuState menu = new MenuState(gsm);
//        gsm.register(StateId.MENU, menu);
//        gsm.set(StateId.MENU);
    }

    public void setScore(int score) {
        this.finalScore = score;
    }

    public void setLevel(int level) {
        this.finalLevel = level;
    }
}

