package hud

import (
	"image/color"

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

	"github.com/atridad/LilGuy/internal/status"
)

type Overlay struct {
	X          int
	Y          int
	Color      color.Color
	ScreenName string
}

func (o Overlay) Draw(screen *ebiten.Image, meters []status.Meter) {
	if o.Color == nil {
		o.Color = color.White
	}

	// Draw background box for instructions
	instrBoxWidth := float32(280)
	instrBoxHeight := float32(78)
	instrBoxPaddingX := float32(12)
	instrBoxPaddingY := float32(15)
	vector.FillRect(screen, 10, 10, instrBoxWidth, instrBoxHeight,
		color.NRGBA{R: 0, G: 0, B: 0, A: 180}, false)
	vector.StrokeRect(screen, 10, 10, instrBoxWidth, instrBoxHeight, 2,
		color.NRGBA{R: 200, G: 200, B: 200, A: 255}, false)

	screenName := o.ScreenName
	if screenName == "" {
		screenName = "Lil Guy"
	}

	instructions := Column{
		Elements: []Element{
			Label{Text: screenName, Color: color.NRGBA{R: 255, G: 255, B: 100, A: 255}},
			Label{Text: "Move with Arrow Keys / WASD", Color: color.NRGBA{R: 230, G: 230, B: 230, A: 255}},
			Label{Text: "Hold Shift to Sprint", Color: color.NRGBA{R: 230, G: 230, B: 230, A: 255}},
		},
		Spacing: 7,
	}
	instructions.Draw(screen, int(10+instrBoxPaddingX), int(10+instrBoxPaddingY))

	// Draw background box for meters
	meterBoxPaddingX := float32(12)
	meterBoxPaddingTop := float32(15)
	meterBoxPaddingBottom := float32(8)
	meterBoxWidth := float32(220)
	meterBoxHeight := float32(meterBoxPaddingTop + meterBoxPaddingBottom + float32(len(meters))*35 - 5)
	meterBoxX := float32(o.X) - meterBoxPaddingX
	meterBoxY := float32(o.Y) - meterBoxPaddingTop
	vector.FillRect(screen, meterBoxX, meterBoxY, meterBoxWidth, meterBoxHeight,
		color.NRGBA{R: 0, G: 0, B: 0, A: 180}, false)
	vector.StrokeRect(screen, meterBoxX, meterBoxY, meterBoxWidth, meterBoxHeight, 2,
		color.NRGBA{R: 200, G: 200, B: 200, A: 255}, false)

	meterElements := make([]Element, 0, len(meters))
	for _, meter := range meters {
		if meter.Base < 0 {
			meterElements = append(meterElements,
				MeterLabel{Meter: meter, Color: color.NRGBA{R: 255, G: 255, B: 255, A: 255}},
			)
		} else {
			meterElements = append(meterElements, Column{
				Elements: []Element{
					MeterLabel{Meter: meter, Color: color.NRGBA{R: 255, G: 255, B: 255, A: 255}},
					Bar{Meter: meter, MaxWidth: 180, Height: 10, ShowBorder: true},
				},
				Spacing: 4,
			})
		}
	}

	meterPanel := Column{
		Elements: meterElements,
		Spacing:  18,
	}
	meterPanel.Draw(screen, o.X, o.Y)
}
