package ui

import (
	"fmt"

	tea "github.com/charmbracelet/bubbletea"
)

func (m *Model) openEnvironmentSelector() {
	m.showEnvSelector = true
	m.showHelp = false
	m.showThemeSelector = false
	if m.cfg.EnvironmentName == "" {
		if len(m.envList.Items()) > 0 {
			m.envList.Select(0)
		}
		return
	}

	for i, item := range m.envList.Items() {
		if env, ok := item.(envItem); ok && env.name == m.cfg.EnvironmentName {
			m.envList.Select(i)
			return
		}
	}

	if len(m.envList.Items()) > 0 {
		m.envList.Select(0)
	}
}

func (m *Model) toggleHelp() {
	if m.showHelp {
		m.showHelp = false
		m.helpJustOpened = false
		m.clearHelpFilter()
		return
	}
	m.showHelp = true
	m.helpJustOpened = true
	m.showEnvSelector = false
	m.showThemeSelector = false
	m.clearHelpFilter()
}

func (m *Model) applyEnvironmentSelection() tea.Cmd {
	item, ok := m.envList.SelectedItem().(envItem)
	if !ok {
		m.showEnvSelector = false
		return nil
	}

	m.showEnvSelector = false
	if m.cfg.EnvironmentName == item.name {
		return nil
	}

	m.cfg.EnvironmentName = item.name
	if gs := m.globalsStore(); gs != nil {
		gs.Clear(item.name)
	}
	if fs := m.fileStore(); fs != nil {
		fs.ClearEnv(item.name)
	}
	msg := fmt.Sprintf("Environment set to %s", item.name)
	m.setStatusMessage(statusMsg{level: statusInfo, text: msg})
	m.syncRequestList(m.doc)
	m.syncHistory()
	return nil
}
