package game

import (
	"log/slog"
	"openquell/assets"
	"openquell/config"
	"openquell/gameui"
	"os"

	"github.com/ebitenui/ebitenui"
	"github.com/ebitenui/ebitenui/widget"

	"github.com/hajimehoshi/ebiten/v2"
)

type MenuScene struct {
	Game     *Game
	Next     SceneName
	Whoami   SceneName
	UseCache bool
	Ui       *ebitenui.UI
}

func NewMenuScene(game *Game) Scene {
	scene := &MenuScene{Whoami: Menu, Game: game, Next: Menu}

	scene.SetupUI()

	return scene
}

func (scene *MenuScene) GetNext() SceneName {
	return scene.Next
}

func (scene *MenuScene) ResetNext() {
	scene.Next = scene.Whoami
}

func (scene *MenuScene) SetLevel(level int) {}

func (scene *MenuScene) SetNext(next SceneName) {
	slog.Debug("select setnext", "next", next)
	scene.Next = next
}

func (scene *MenuScene) Clearscreen() bool {
	return true
}

func (scene *MenuScene) Update() error {
	scene.Ui.Update()
	return nil
}

func (scene *MenuScene) Draw(screen *ebiten.Image) {
	scene.Ui.Draw(screen)
}

func (scene *MenuScene) SetupUI() {
	rowContainer := gameui.NewRowContainer()

	buttonStartnew := gameui.NewMenuButton("Start new game", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(Play)
		})

	buttonMenuLevel := gameui.NewMenuButton("Select Level", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(Select)
		})

	buttonAbout := gameui.NewMenuButton("About this game", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(About)
		})

	buttonQuit := gameui.NewMenuButton("Quit Game", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			os.Exit(1) // FIXME: present another scene "are you sure and/or thank you"
		})

	label := widget.NewText(
		widget.TextOpts.Text("Menu", *assets.FontRenderer.FontBig, config.FontColorFG),
		widget.TextOpts.Position(widget.TextPositionCenter, widget.TextPositionCenter),
	)

	rowContainer.AddChild(label)
	rowContainer.AddChild(buttonStartnew)
	rowContainer.AddChild(buttonMenuLevel)
	rowContainer.AddChild(buttonAbout)
	rowContainer.AddChild(buttonQuit)

	scene.Ui = &ebitenui.UI{
		Container: rowContainer.Container(),
	}
}
