package main

import (
	"fmt"
	"os"

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

type model struct {
	textInput      textinput.Model
	width          int
	height         int
	sidebarContent string
}

func initialModel() model {
	ti := textinput.New()
	ti.Placeholder = "Search"
	ti.Width = 30
	ti.CharLimit = 30
	ti.Prompt = ""
	ti.Focus()
	return model{
		textInput:      ti,
		sidebarContent: "Library\n\nPlaylist 1\nPlaylist 2\nFavorites",
	}
}

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

func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmd tea.Cmd
	switch msg := msg.(type) {
	case tea.KeyMsg:
		switch msg.String() {
		case "q", "ctrl+c":
			return m, tea.Quit
		}
	case tea.WindowSizeMsg:
		m.width = msg.Width
		m.height = msg.Height
	}
	m.textInput, cmd = m.textInput.Update(msg)
	return m, cmd
}

func (m model) View() string {
	if m.width == 0 {
		return "loading..."
	}

	// Create search box
	searchBox := lipgloss.NewStyle().BorderStyle(lipgloss.ThickBorder()).Padding(0, 1).Render(m.textInput.View())

	// Create sidebar
	sidebar := lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).Padding(1, 2).Render(m.sidebarContent)

	// Combine search and sidebar vertically
	content := lipgloss.JoinVertical(lipgloss.Left, searchBox, "\n", sidebar)

	return lipgloss.Place(
		m.width,
		m.height,
		lipgloss.Center,
		lipgloss.Center,
		content,
	)
}

func main() {
	p := tea.NewProgram(initialModel(), tea.WithAltScreen())
	if _, err := p.Run(); err != nil {
		fmt.Println("Error:", err)
		os.Exit(1)
	}
}
