use crossterm::event::{KeyCode, KeyEvent};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Quit,
    Up,
    Down,
    Top,
    Bottom,
    Add,
    Edit,
    Delete,
    MarkDone,
    UndoDone,
    Move,
    NewSubtask,
    ToggleSubtask,
    Color,
    Tab,
    SelectColor(usize), // 0-7
    ReorderUp,
    ReorderDown,
    CompleteTask,
    ToggleNotes,
    None,
}

pub fn map_key(key: KeyEvent) -> Action {
    match key.code {
        KeyCode::Char('q') | KeyCode::Esc => Action::Quit,
        KeyCode::Char('k') | KeyCode::Up => {
            if key.modifiers.contains(crossterm::event::KeyModifiers::SHIFT) {
                Action::ReorderUp
            } else {
                Action::Up
            }
        },
        KeyCode::Char('j') | KeyCode::Down => {
            if key.modifiers.contains(crossterm::event::KeyModifiers::SHIFT) {
                Action::ReorderDown
            } else {
                Action::Down
            }
        },
        KeyCode::Char('K') => Action::ReorderUp,
        KeyCode::Char('J') => Action::ReorderDown,
        KeyCode::Char('g') => Action::Top, // Simplified, vim 'gg' implies state
        KeyCode::Char('G') => Action::Bottom,
        KeyCode::Char('a') => Action::Add,
        KeyCode::Enter => Action::Edit,
        KeyCode::Char('d') => Action::Delete,
        KeyCode::Char('x') => Action::MarkDone, // or 'd' also? instructions say 'd' or 'x'. Let's map 'x' to done, 'd' to delete confirms.
        KeyCode::Char('u') => Action::UndoDone,
        KeyCode::Char('m') => Action::Move,
        KeyCode::Char('s') => Action::NewSubtask,
        KeyCode::Char('n') => Action::ToggleNotes,
        KeyCode::Char(' ') => Action::ToggleSubtask,
        KeyCode::Char('c') => Action::Color,
        KeyCode::Char('C') => Action::CompleteTask,
        KeyCode::Tab => Action::Tab,
        KeyCode::Char(c) if c.is_ascii_digit() => {
             if let Some(digit) = c.to_digit(10) {
                 if digit <= 7 { Action::SelectColor(digit as usize) } else { Action::None }
             } else { Action::None }
        },
        _ => Action::None,
    }
}
