//! Help screen displaying keyboard shortcuts and navigation
//!
//! This module provides a comprehensive keyboard shortcuts reference
//! organized by context (global, tasks, themes, etc.)

// Note: This is a binary module
use crate::app::App;
use crate::theme::AppTheme;
use ratatui::{
    layout::{Alignment, Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
    Frame,
};

/// Keyboard shortcut group
#[derive(Debug, Clone)]
pub(crate) struct ShortcutGroup {
    /// Group title
    pub title: &'static str,
    /// Shortcuts (key, description)
    pub shortcuts: Vec<(&'static str, &'static str)>,
}

/// Get all shortcut groups
pub(crate) fn get_shortcut_groups() -> Vec<ShortcutGroup> {
    vec![
        ShortcutGroup {
            title: "Global",
            shortcuts: vec![
                ("q, Esc", "Quit / Go back"),
                ("?, F1, Ctrl+H", "Show this help"),
                ("Ctrl+C", "Force quit"),
            ],
        },
        ShortcutGroup {
            title: "Tasks",
            shortcuts: vec![
                ("↑/k, ↓/j", "Navigate up/down"),
                ("Space", "Toggle task completion"),
                ("n", "Create new task"),
                ("e", "Edit selected task"),
                ("d, Del", "Delete task"),
                ("/", "Filter/Search tasks"),
                ("m", "Load more tasks (pagination)"),
                ("a", "View attachments (planned)"),
                ("c", "View comments (planned)"),
            ],
        },
        ShortcutGroup {
            title: "Projects",
            shortcuts: vec![
                ("↑/k, ↓/j", "Navigate projects"),
                ("Enter", "Select project"),
                ("c", "Create new project"),
                ("t", "View project tasks"),
                ("s", "View security assessment"),
                ("b", "Back to projects list"),
            ],
        },
        ShortcutGroup {
            title: "Task Editing",
            shortcuts: vec![
                ("Ctrl+Enter", "Submit task"),
                ("Esc", "Cancel editing"),
                ("Enter", "New line"),
                ("Backspace", "Delete character"),
            ],
        },
        ShortcutGroup {
            title: "Filters & Search",
            shortcuts: vec![
                ("f", "Toggle completion filter"),
                ("c", "Clear all filters"),
                ("↑/k, ↓/j", "Navigate sort options"),
                ("Enter", "Apply selected sort"),
                ("Type...", "Search task description"),
                ("Backspace", "Delete search character"),
            ],
        },
        ShortcutGroup {
            title: "Themes",
            shortcuts: vec![
                ("T", "Open theme selector"),
                ("Ctrl+D", "Toggle dark mode"),
                ("↑/k, ↓/j", "Navigate themes (in selector)"),
                ("Enter", "Apply selected theme"),
            ],
        },
        ShortcutGroup {
            title: "Layout",
            shortcuts: vec![
                ("Ctrl+R", "Reset layout to defaults"),
                ("[, ]", "Adjust detail panel width (planned)"),
            ],
        },
        ShortcutGroup {
            title: "Delete Confirmation",
            shortcuts: vec![
                ("y, Enter", "Confirm deletion (modal/prompt)"),
                ("n, Esc", "Cancel deletion"),
                ("d (twice)", "Confirm deletion (inline mode)"),
            ],
        },
    ]
}

/// Render help screen
pub(crate) fn render_help_screen(f: &mut Frame<'_>, app: &App, area: Rect, theme: &AppTheme) {
    // Create layout
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Content
            Constraint::Length(3), // Footer
        ])
        .split(area);

    // Render header
    let header = Paragraph::new(vec![Line::from(vec![Span::styled(
        "⌨️  Keyboard Shortcuts",
        theme.header_style(),
    )])])
    .block(
        Block::default()
            .borders(Borders::ALL)
            .border_style(theme.border_style()),
    )
    .alignment(Alignment::Center);
    f.render_widget(header, chunks[0]);

    // Get all shortcut groups
    let groups = get_shortcut_groups();

    // Calculate total items for scrolling
    let mut total_lines = 0;
    for group in &groups {
        total_lines += 2; // Group header + spacing
        total_lines += group.shortcuts.len();
    }

    // Build content lines
    let mut lines: Vec<Line<'_>> = Vec::new();

    for (i, group) in groups.iter().enumerate() {
        // Group header
        lines.push(Line::from(""));
        lines.push(Line::from(vec![Span::styled(
            format!("▸ {}", group.title),
            theme.section_header_style().add_modifier(Modifier::BOLD),
        )]));

        // Shortcuts
        for (key, desc) in &group.shortcuts {
            lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(
                    format!("{:20}", key),
                    Style::default()
                        .fg(theme.base.primary)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(" → "),
                Span::styled(*desc, theme.list_item_style()),
            ]));
        }

        // Add spacing between groups (except last)
        if i < groups.len() - 1 {
            lines.push(Line::from(""));
        }
    }

    // Apply scroll offset
    let visible_height = chunks[1].height.saturating_sub(2) as usize; // Account for borders
    let scroll_offset = app
        .help_scroll_offset
        .min(lines.len().saturating_sub(visible_height));
    let visible_lines: Vec<Line<'_>> = lines
        .into_iter()
        .skip(scroll_offset)
        .take(visible_height)
        .collect();

    // Render content
    let content = Paragraph::new(visible_lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme.border_style())
                .title(" Help "),
        )
        .alignment(Alignment::Left);
    f.render_widget(content, chunks[1]);

    // Render footer with instructions
    let footer_text = vec![Line::from(vec![
        Span::styled("↑/↓", theme.success_style().add_modifier(Modifier::BOLD)),
        Span::raw(" Scroll  "),
        Span::styled("Esc/q", theme.success_style().add_modifier(Modifier::BOLD)),
        Span::raw(" Close  "),
        Span::styled(
            format!(
                "Line {}/{} ",
                scroll_offset + 1,
                total_lines.max(visible_height)
            ),
            theme.metadata_style(),
        ),
    ])];

    let footer = Paragraph::new(footer_text)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(theme.border_style()),
        )
        .alignment(Alignment::Center);
    f.render_widget(footer, chunks[2]);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_shortcut_groups() {
        let groups = get_shortcut_groups();
        assert!(!groups.is_empty());
        assert!(groups.len() >= 7); // At least 7 categories

        // Verify each group has content
        for group in groups {
            assert!(!group.title.is_empty());
            assert!(!group.shortcuts.is_empty());
        }
    }

    #[test]
    fn test_shortcut_group_structure() {
        let groups = get_shortcut_groups();

        // Verify Global shortcuts exist
        let global = groups.iter().find(|g| g.title == "Global");
        assert!(global.is_some());

        // Verify Tasks shortcuts exist
        let tasks = groups.iter().find(|g| g.title == "Tasks");
        assert!(tasks.is_some());
    }
}
