package screens

import (
	"charm.land/bubbles/v2/key"
	tea "charm.land/bubbletea/v2"

	"charm.land/huh/v2"

	"git.secluded.site/keld/internal/theme"
	"git.secluded.site/keld/internal/ui"
)

// Target is a Screen adapter that wraps a huh Input for entering
// the restore target directory. It validates that the input is
// non-empty and returns the entered path via [Value].
type Target struct {
	styles    *theme.Styles
	form      *huh.Form
	entered   string
	selection string
}

// NewTarget creates a target directory screen. The styles pointer
// should come from the session so theme updates propagate.
func NewTarget(styles *theme.Styles) *Target {
	return &Target{
		styles: styles,
	}
}

// buildForm constructs the huh form. Called from Init when the form
// needs (re)building.
func (t *Target) buildForm() {
	// Preserve any previous selection so back-navigation shows the
	// user's earlier input. Reset the breadcrumb label since the
	// screen is being re-activated.
	t.selection = ""

	input := huh.NewInput().
		Title("Restore destination").
		Placeholder("e.g. /tmp/restore").
		Value(&t.entered).
		Validate(huh.ValidateNotEmpty())

	t.form = huh.NewForm(
		huh.NewGroup(input),
	).WithTheme(t.styles.Huh).WithShowHelp(false)
}

// Init initialises the embedded form. On first call or after
// completion, the form is (re)built so it picks up the current
// theme and can accept input again.
func (t *Target) Init() tea.Cmd {
	if t.form == nil || t.form.State != huh.StateNormal {
		t.buildForm()
	}
	return t.form.Init()
}

// Update handles messages. Esc is intercepted for back navigation.
// All other messages are forwarded to the huh form.
func (t *Target) Update(msg tea.Msg) (ui.Screen, tea.Cmd) {
	if t.form == nil {
		return t, nil
	}

	switch msg.(type) {
	case tea.BackgroundColorMsg:
		t.buildForm()
		return t, t.form.Init()
	}

	if kp, ok := msg.(tea.KeyPressMsg); ok {
		if kp.Code == tea.KeyEscape {
			return t, ui.BackCmd
		}
	}

	model, cmd := t.form.Update(msg)
	if f, ok := model.(*huh.Form); ok {
		t.form = f
	}

	if t.form.State == huh.StateCompleted {
		t.selection = t.entered
		return t, ui.DoneCmd
	}

	return t, cmd
}

// View renders the form.
func (t *Target) View() string {
	if t.form == nil {
		return ""
	}
	return t.form.View()
}

// Title returns the screen's display title.
func (t *Target) Title() string { return "Target directory" }

// KeyBindings returns bindings for the help bar.
func (t *Target) KeyBindings() []key.Binding {
	return []key.Binding{
		key.NewBinding(key.WithKeys("enter"), key.WithHelp("enter", "confirm")),
	}
}

// Selection returns the entered path for breadcrumb display, or ""
// if nothing has been entered yet.
func (t *Target) Selection() string { return t.selection }

// Value returns the entered target directory path.
func (t *Target) Value() string { return t.entered }
