package steps

import (
	"miasma-installer/tui/styles"
	"strings"

	"github.com/charmbracelet/bubbles/textinput"
	tea "github.com/charmbracelet/bubbletea"
)

type HostnameModel struct {
	Hostname string
	input    textinput.Model
	Finished bool
}

func NewHostnameModel() HostnameModel {
	ti := textinput.New()
	ti.Placeholder = "miasma"
	ti.Focus()
	ti.CharLimit = 63
	ti.Width = 40

	return HostnameModel{
		input: ti,
	}
}

func (m HostnameModel) Init() tea.Cmd {
	return textinput.Blink
}

func (m HostnameModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	if m.Finished {
		return m, nil
	}

	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "enter":
			if m.input.Value() != "" {
				m.Hostname = m.input.Value()
				m.Finished = true
				return m, nil
			}
		}
	}

	var cmd tea.Cmd
	m.input, cmd = m.input.Update(msg)
	return m, cmd
}

func (m HostnameModel) View() string {
	var content strings.Builder

	content.WriteString(styles.TitleStyle.Render("💻 System Hostname"))
	content.WriteString("\n\n")

	info := "Choose a name for your computer.\nThis will be used to identify your system on the network."
	content.WriteString(styles.InfoBoxStyle.Render(info))
	content.WriteString("\n\n")

	content.WriteString(styles.LabelStyle.Render("Hostname:"))
	content.WriteString("\n")
	content.WriteString(styles.FocusedInputStyle.Render(m.input.View()))
	content.WriteString("\n\n")

	content.WriteString(styles.RenderHelp("Enter", "Continue"))

	return styles.AppStyle.Render(content.String())
}
