package steps

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

	tea "github.com/charmbracelet/bubbletea"
)

type ConfirmModel struct {
	Disk       string
	EnableLUKS bool
	Hostname   string
	Username   string
	Confirmed  bool
	Finished   bool
}

func NewConfirmModel(disk string, enableLUKS bool, hostname string, username string) ConfirmModel {
	return ConfirmModel{
		Disk:       disk,
		EnableLUKS: enableLUKS,
		Hostname:   hostname,
		Username:   username,
	}
}

func (m ConfirmModel) Init() tea.Cmd {
	return nil
}

func (m ConfirmModel) 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 "y":
			m.Confirmed = true
			m.Finished = true
			return m, nil
		case "n":
			m.Confirmed = false
			m.Finished = true
			return m, nil
		}
	}

	return m, nil
}

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

	content.WriteString(styles.TitleStyle.Render("✓ Confirm Installation"))
	content.WriteString("\n\n")

	content.WriteString("Review your installation settings:\n\n")

	settings := []string{
		styles.RenderKeyValue("Disk", m.Disk),
		styles.RenderKeyValue("Encryption", map[bool]string{true: "Enabled (LUKS2)", false: "Disabled"}[m.EnableLUKS]),
		styles.RenderKeyValue("Hostname", m.Hostname),
		styles.RenderKeyValue("Username", m.Username),
		styles.RenderKeyValue("Filesystem", "btrfs"),
		styles.RenderKeyValue("Desktop", "Cosmic Desktop"),
		styles.RenderKeyValue("Kernel", "linux-hardened"),
		styles.RenderKeyValue("Bootloader", "systemd-boot (UEFI)"),
	}

	content.WriteString(styles.BoxStyle.Render(strings.Join(settings, "\n")))
	content.WriteString("\n\n")

	warning := fmt.Sprintf("⚠️  WARNING: This will ERASE ALL DATA on %s", m.Disk)
	content.WriteString(styles.WarningBoxStyle.Render(warning))
	content.WriteString("\n\n")

	content.WriteString(styles.RenderHelp("y", "Proceed with installation", "n", "Cancel"))

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