package eu.midnightdust.yaytris.ui;

import eu.midnightdust.yaytris.util.CatppuccinColor;

import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import static eu.midnightdust.yaytris.Translation.t;
import static eu.midnightdust.yaytris.ui.TetrisUI.scale;

public class ScoreMenu extends AbstractMenu {
    final TetrisUI ui;
    final PreviewCanvas previewCanvas;
    final JLabel gameOverLabel;
    final JLabel currentScoreLabel;
    final JLabel currentLevelLabel;
    final JLabel currentTimeLabel;

    ScoreMenu(int x, int y, int width, int height, TetrisUI ui) {
        this.ui = ui;
        this.setBounds(x, y, width, height);
        this.setLayout(null);

        this.previewCanvas = new PreviewCanvas(ui);
        this.previewCanvas.setBounds(scale(92), scale(4), scale(40), scale(40));
        this.previewCanvas.setBackground(Color.BLACK);
        this.previewCanvas.setBorder(new LineBorder(CatppuccinColor.SURFACE0.getColor()));
        this.add(previewCanvas, 0);

        this.gameOverLabel = new JLabel();
        this.add(gameOverLabel);

        this.currentScoreLabel = new JLabel(t("game.score", "0"));
        this.add(currentScoreLabel);

        this.currentLevelLabel = new JLabel(t("game.level", "0"));
        this.add(currentLevelLabel);

        this.currentTimeLabel = new JLabel(t("game.time", "00:00"));
        this.add(currentTimeLabel);

        JButton backButton = new JButton(t("ui.back"));
        backButton.addActionListener(ui::openMainMenu);
        this.add(backButton);
    }

    public void updateScore(int score) {
        this.currentScoreLabel.setText(t("game.score", score));
        this.repaint();
    }

    public void updateTime(LocalTime startingTime) {
        LocalTime timeElapsed = LocalTime.ofNanoOfDay(LocalTime.now().toNanoOfDay() - startingTime.toNanoOfDay());

        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern(timeElapsed.getHour() > 0 ? "HH:mm:ss" : "mm:ss");
        this.currentTimeLabel.setText(t("game.time", timeFormatter.format(timeElapsed)));
        this.repaint();
    }

    public void gameOver() {
        this.gameOverLabel.setText(t("game.over"));
    }

    public void updateLevel(int level) {
        this.currentLevelLabel.setText(t("game.level", level));
        this.repaint();
    }

    @Override
    public int getSpacing() {
        return 17;
    }
}
