package tui

import (
	"fmt"
	"slices"
	"strconv"
	"strings"

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

type Dialog struct {
	action   ProcessAction
	pids     map[int32]bool
	pointPid *int32
}

var (
	BottonStyle    = lipgloss.NewStyle().Border(lipgloss.NormalBorder())
	BottonActStyle = lipgloss.NewStyle().Border(lipgloss.DoubleBorder()).Foreground(lipgloss.Color("#fd3535ff")).Underline(true)
)

func (d *Dialog) SetAction(ac ProcessAction) {
	d.action = ac
}

func NewDialog(pids map[int32]bool) *Dialog {
	return &Dialog{
		action:   PANone,
		pids:     pids,
		pointPid: nil,
	}
}

func (d *Dialog) Init() tea.Cmd {
	return nil
}

func (d *Dialog) Update(imsg tea.Msg) (tea.Model, tea.Cmd) {
	switch msg := imsg.(type) {
	case *ActionMsg:
		d.action = *msg.Action
		d.pids = msg.SelectPids
		d.pointPid = msg.PointPid
		return d, nil
	}
	return d, nil
}

func (d *Dialog) View() string {
	str := "Send a signal to the following process?\n"
	width := lipgloss.Width(str)
	sty := lipgloss.NewStyle().Width(width).Align(lipgloss.Left)
	sb := strings.Builder{}
	sb.WriteString(str)
	if d.pids != nil {
		pids := make([]int, 0, len(d.pids))
		for pid, have := range d.pids {
			if have {
				pids = append(pids, int(pid))
			}
		}
		slices.Sort(pids)
		for _, pid := range pids {
			strPid := strconv.Itoa(int(pid))
			sb.WriteString(sty.Render(" · "+strPid) + "\n")

		}
	} else if d.pointPid != nil {
		strPid := strconv.Itoa(int(*d.pointPid))
		sb.WriteString(sty.Render(" · "+strPid) + "\n")
	}

	killButton := BottonStyle.Render(PAKill.String())
	termButton := BottonStyle.Render(PATerm.String())
	intButton := BottonStyle.Render(PAInt.String())
	cancelButton := BottonStyle.Render(PANone.String())
	switch d.action {
	case PAInt:
		intButton = BottonActStyle.Render(PAInt.String())
	case PATerm:
		termButton = BottonActStyle.Render(PATerm.String())
	case PAKill:
		killButton = BottonActStyle.Render(PAKill.String())
	default:
		cancelButton = BottonActStyle.Render(PANone.String())
	}
	buttons := lipgloss.JoinHorizontal(lipgloss.Top, killButton, termButton, intButton, cancelButton)
	buttons = sty.Align(lipgloss.Center).Render(buttons)
	sb.WriteString(buttons)
	str = lipgloss.NewStyle().Width(width+4).Align(lipgloss.Center).Border(lipgloss.DoubleBorder()).Padding(0, 2).Render(sb.String())
	return fmt.Sprintf("%s\n", str)
}
