package handlers

import (
	"tetris/assets"
	"tetris/engine/audio"
	"tetris/engine/core"
	"tetris/engine/render"
	"tetris/game"
	"tetris/game/state"
	"tetris/game/ui"
	"tetris/game/ui/layouts"
	"tetris/game/ui/widgets"
	"tetris/game/uievents"

	rl "github.com/gen2brain/raylib-go/raylib"
)

type OptionsMenu struct {
	sndVolume *widgets.Slider
	list      *layouts.ListBox
}

func soundVolumeChanged(widget *widgets.Slider) {
	value := core.ByteToClampedFloat32(byte(widget.Value))

	audio.SetVolume(value)
	audio.Play(assets.SFX_MENU_SOUND_VOLUME_SELECT)

	// Store in config and save
	game.Config.SoundVolume = byte(widget.Value)
	game.Config.Save()
}

func NewOptionsMenu() *OptionsMenu {
	sndVolume := widgets.NewSlider(0, 255, 10).WithOnChange(soundVolumeChanged)
	return &OptionsMenu{
		sndVolume: sndVolume,
		list: layouts.NewListBox([]ui.InputWidget{
			layouts.NewInputControl(widgets.NewLabel("Sound Volume", 16), sndVolume),
		}).Spacing(10).OnSelect(uievents.MenuSelect),
	}
}

func (menu *OptionsMenu) Enter() {
	vol := core.ClampedFloat32ToByte(audio.Volume())
	menu.sndVolume.SetValue(int(vol))
}

func (OptionsMenu) Exit() {
}

func (menu *OptionsMenu) Update(fsm state.Transitioner, delta float32) {
	if rl.IsKeyPressed(rl.KeyEscape) {
		fsm.Switch("menu")
	} else {
		menu.list.HandleInput()
	}
}

func (opt OptionsMenu) Render() {
	render.Begin(rl.Black)

	render.DrawTextCenter(340, 100, 32, "Options", rl.White)
	opt.list.Draw(150, 200)

	render.End()
}
