package app

import (
	"fmt"

	ui "github.com/metaspartan/gotui/v5"
	"github.com/metaspartan/mactop/v2/internal/i18n"
)

// isLightNamedTheme returns true for named themes that need dark text on header
// Only indigo is dark enough to need white text
func isLightNamedTheme(theme string) bool {
	return theme != "indigo"
}

func resolveProcessThemeColor() (string, string) {
	themeColor := processList.TextStyle.Fg
	var themeColorStr string

	// Check if custom ProcessList color is set
	if currentConfig.CustomTheme != nil && currentConfig.CustomTheme.ProcessList != "" {
		if IsHexColor(currentConfig.CustomTheme.ProcessList) {
			themeColorStr = currentConfig.CustomTheme.ProcessList
		}
	}

	if themeColorStr == "" {
		// Check if the theme is a hex color
		if IsHexColor(currentConfig.Theme) {
			themeColorStr = currentConfig.Theme
		} else if IsCatppuccinTheme(currentConfig.Theme) {
			themeColorStr = GetCatppuccinHex(currentConfig.Theme, "Primary")
		} else if IsLightMode && currentConfig.Theme == "white" {
			themeColorStr = "black"
		} else if currentConfig.Theme == "1977" {
			themeColorStr = "green"
		} else if color, ok := colorMap[currentConfig.Theme]; ok {
			hexStr := resolveThemeColorString(currentConfig.Theme)
			if hexStr != currentConfig.Theme {
				themeColorStr = hexStr
			} else {
				themeColorStr = getThemeColorName(color)
			}
		} else {
			themeColorStr = getThemeColorName(themeColor)
		}
	}

	return themeColorStr, resolveSelectedHeaderFg(themeColorStr)
}

// resolveSelectedHeaderFg determines the foreground color for selected headers
// based on the theme color, ensuring good contrast.
func resolveSelectedHeaderFg(themeColorStr string) string {
	if themeColorStr == "black" || themeColorStr == "#000000" || themeColorStr == "#020202" {
		return "#ffffff"
	}
	if IsLightMode {
		return "#020202"
	}
	if IsCatppuccinTheme(currentConfig.Theme) {
		return GetCatppuccinHex(currentConfig.Theme, "Base")
	}
	if IsHexColor(themeColorStr) {
		if IsLightHexColor(themeColorStr) {
			return "#020202"
		}
		return "#ffffff"
	}
	if isLightNamedTheme(currentConfig.Theme) {
		return "#020202"
	}
	return "#ffffff"
}

func getProcessListTitle() (string, ui.Style) {
	// Resolve title color (use process list color if set)
	var titleColor ui.Color = ui.ColorClear
	if currentConfig.CustomTheme != nil && currentConfig.CustomTheme.ProcessList != "" {
		if color, err := ParseHexColor(currentConfig.CustomTheme.ProcessList); err == nil {
			titleColor = color
		}
	}
	if titleColor == ui.ColorClear {
		titleColor = GetThemeColorWithLightMode(currentConfig.Theme, IsLightMode)
	}

	if killPending {
		return fmt.Sprintf(i18n.T("TUI_ProcessListKill"), killPID), ui.NewStyle(ui.ColorRed, CurrentBgColor, ui.ModifierBold)
	} else if searchMode || searchText != "" {
		return fmt.Sprintf(i18n.T("TUI_ProcessListSearch"), searchText), ui.NewStyle(titleColor, CurrentBgColor, ui.ModifierBold)
	} else if isFrozen {
		return i18n.T("TUI_ProcessListFrozen"), ui.NewStyle(titleColor, CurrentBgColor, ui.ModifierBold)
	} else if filterPID > 0 {
		return fmt.Sprintf(i18n.T("TUI_ProcessListPID"), filterPID), ui.NewStyle(titleColor, CurrentBgColor, ui.ModifierBold)
	}
	return i18n.T("TUI_ProcessListFull"), ui.NewStyle(titleColor, CurrentBgColor)
}

func attemptKillProcess() {
	var currentViewProcesses []ProcessMetrics

	// If search criteria exists, use that (even if nil/empty), otherwise use full list
	if searchText != "" {
		if filteredProcesses == nil {
			currentViewProcesses = []ProcessMetrics{}
		} else {
			currentViewProcesses = filteredProcesses
		}
	} else {
		currentViewProcesses = lastProcesses
	}

	if len(currentViewProcesses) > 0 && processList.SelectedRow < len(currentViewProcesses)+1 {
		if processList.SelectedRow > 0 {
			processIndex := processList.SelectedRow - 1
			if processIndex < len(currentViewProcesses) {
				pid := currentViewProcesses[processIndex].PID
				showKillModal(pid)
			}
		}
	}
}

func handleSearchToggle() {
	searchMode = true
	searchText = ""
	filteredProcesses = nil
	updateProcessList()
}

func handleSearchClear() {
	if searchText != "" {
		searchText = ""
		filteredProcesses = nil
		updateProcessList()
	}
}

func handleVerticalNavigation(e ui.Event) {
	switch e.ID {
	case "<Up>", "k", "<MouseWheelUp>":
		if processList.SelectedRow > 0 {
			processList.SelectedRow--
			updateProcessList()
		}
	case "<Down>", "j", "<MouseWheelDown>":
		if processList.SelectedRow < len(processList.Rows)-1 {
			processList.SelectedRow++
			updateProcessList()
		}
	case "g", "<Home>":
		if len(processList.Rows) > 1 {
			processList.SelectedRow = 1
			updateProcessList()
		} else {
			processList.SelectedRow = 0
		}
	case "G", "<End>":
		if len(processList.Rows) > 0 {
			processList.SelectedRow = len(processList.Rows) - 1
			updateProcessList()
		}
	}
}

func handleColumnNavigation(e ui.Event) {
	switch e.ID {
	case "<Left>":
		if selectedColumn > 0 {
			selectedColumn--
			currentConfig.SortColumn = &selectedColumn
			saveConfig()
			updateProcessList()
		}
	case "<Right>":
		if selectedColumn < len(columns)-1 {
			selectedColumn++
			currentConfig.SortColumn = &selectedColumn
			saveConfig()
			updateProcessList()
		}
	case "<Enter>", "<Space>":
		handleSortToggle()
	}
}

func handleSortToggle() {
	sortReverse = !sortReverse
	currentConfig.SortReverse = sortReverse
	saveConfig()
	updateProcessList()
}
