use crate::parser::Process;
use colored::*;
use std::io::{self, Write};

pub fn display_processes(processes: &[Process]) {
    if processes.len() == 1 {
        let p = &processes[0];
        println!(
            "  {} {} ({})",
            "PID".bold(),
            p.pid.to_string().cyan(),
            p.command.bold()
        );
    } else {
        for (i, p) in processes.iter().enumerate() {
            println!(
                "[{}]  {} {} ({})",
                (i + 1).to_string().yellow(),
                "PID".bold(),
                p.pid.to_string().cyan(),
                p.command.bold()
            );
        }
    }
}

pub fn prompt_confirmation() -> bool {
    print!("\n{} (y/n): ", "Kill?".bold().red());
    io::stdout().flush().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    input.trim().to_lowercase() == "y"
}

pub fn prompt_selection(max: usize) -> Option<Selection> {
    print!(
        "\n{} (1-{}), '{}' for all, '{}' to quit: ",
        "Select process to kill".bold(),
        max,
        "a".yellow(),
        "q".red()
    );
    io::stdout().flush().unwrap();

    let mut input = String::new();
    io::stdin().read_line(&mut input).unwrap();
    let choice = input.trim().to_lowercase();

    if choice == "a" {
        Some(Selection::All)
    } else if choice == "q" {
        None
    } else if let Ok(idx) = choice.parse::<usize>() {
        if idx >= 1 && idx <= max {
            Some(Selection::Index(idx - 1))
        } else {
            None
        }
    } else {
        None
    }
}

pub enum Selection {
    Index(usize),
    All,
}
