package game

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

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

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

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

func NewPopupScene(game *Game) Scene {
	scene := &PopupScene{Whoami: Popup, Game: game, Next: Popup}

	scene.SetupUI()

	return scene
}

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

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

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

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

func (scene *PopupScene) Clearscreen() bool {
	// both level_scene AND the popup must not clear to get an actual popup
	return false
}

func (scene *PopupScene) Update() error {
	scene.Ui.Update()

	if inpututil.IsKeyJustPressed(ebiten.KeyEscape) {
		scene.SetNext(Play)
	}

	return nil
}

func (scene *PopupScene) Draw(screen *ebiten.Image) {
	background := assets.Assets["background-popup"]

	op := &ebiten.DrawImageOptions{}
	op.GeoM.Translate(
		float64((scene.Game.ScreenWidth/2)-(background.Bounds().Dx()/2)),
		float64((scene.Game.ScreenHeight/2)-(background.Bounds().Dy()/2)),
	)

	screen.DrawImage(assets.Assets["background-popup"], op)

	scene.Ui.Draw(screen)
}

func (scene *PopupScene) SetupUI() {
	observer := observers.GetGameObserver(scene.Game.World)

	rowContainer := gameui.NewRowContainer(false)

	buttonContinue := gameui.NewMenuButton("Continue", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(Play)
		})

	buttonAbort := gameui.NewMenuButton("Abort", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(Menu)
		})

	buttonRetry := gameui.NewMenuButton("Retry", *assets.FontRenderer.FontNormal,
		func(args *widget.ButtonClickedEventArgs) {
			scene.SetNext(Play)
			observer.Retry = true
		})

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

	rowContainer.AddChild(label)
	rowContainer.AddChild(buttonContinue)
	rowContainer.AddChild(buttonRetry)
	rowContainer.AddChild(buttonAbort)

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