package layouts

import (
	"tetris/game/ui"
	"tetris/game/ui/base"

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

type OnSelectCallback func()

type ListBox struct {
	*base.WithFocus
	selected int
	entries  []ui.InputWidget
	onSelect OnSelectCallback
	spacing  int
}

func NewListBox(entries []ui.InputWidget) *ListBox {
	lb := &ListBox{
		WithFocus: &base.WithFocus{},
		entries:   entries,
		onSelect:  func() {},
	}
	lb.entries[0].SetFocus(true)
	return lb
}

func (lb *ListBox) Spacing(value int) *ListBox {
	lb.spacing = value
	return lb
}

func (lb *ListBox) OnSelect(callback OnSelectCallback) *ListBox {
	lb.onSelect = callback
	return lb
}

func (lb ListBox) Entries() []ui.InputWidget {
	return lb.entries
}

func (lb *ListBox) Select(index int) {
	if lb.SetSelected(index) {
		lb.onSelect()
	}
}

func (lb *ListBox) SetSelected(index int) bool {
	if index >= 0 && index < len(lb.entries) {
		lb.entries[lb.selected].SetFocus(false)
		lb.selected = index
		lb.entries[lb.selected].SetFocus(true)
		return true
	}
	return false
}

func (lb ListBox) Selected() ui.InputWidget {
	return lb.entries[lb.selected]
}

func (lb ListBox) IsSelected(index int) bool {
	return lb.selected == index
}

func (lb *ListBox) Next() {
	lb.Select(lb.selected + 1)
}

func (lb *ListBox) Previous() {
	lb.Select(lb.selected - 1)
}

func (lb *ListBox) HandleInput() {
	if rl.IsKeyPressed(rl.KeyDown) {
		lb.Next()
	} else if rl.IsKeyPressed(rl.KeyUp) {
		lb.Previous()
	} else {
		lb.Selected().HandleInput()
	}
}

func (lb *ListBox) Draw(x, y int32) {
	for _, ent := range lb.entries {
		ent.Draw(x, y)
		y += int32(ent.Size().Y + lb.spacing)
	}
}
