use crate::app::AppState;
/// Help popup screen
/// Professional, organized command reference - REDESIGNED
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};

// === 4RUNR BRAND COLORS ===
const BRAND_PURPLE: Color = Color::Rgb(138, 43, 226);
const CYBER_CYAN: Color = Color::Rgb(0, 255, 255);
const NEON_GREEN: Color = Color::Rgb(57, 255, 20);
const AMBER_WARN: Color = Color::Rgb(255, 191, 0);
const TEXT_PRIMARY: Color = Color::Rgb(230, 230, 240);
const TEXT_DIM: Color = Color::Rgb(100, 100, 120);
const BG_PANEL: Color = Color::Rgb(18, 18, 25);

/// Render help popup overlay
pub fn render_help(f: &mut Frame, area: Rect, _state: &AppState) {
    // Render background overlay (dimmed)
    let overlay = Block::default().style(Style::default().bg(Color::Black));
    f.render_widget(overlay, area);

    // Calculate popup size (85% width, 90% height, centered)
    let popup_width = (area.width * 85 / 100).max(70);
    let popup_height = (area.height * 90 / 100).max(25);
    let popup_x = (area.width.saturating_sub(popup_width)) / 2;
    let popup_y = (area.height.saturating_sub(popup_height)) / 2;

    let popup_area = Rect {
        x: popup_x,
        y: popup_y,
        width: popup_width,
        height: popup_height,
    };

    // Render help popup
    render_help_content(f, popup_area);
}

fn render_help_content(f: &mut Frame, area: Rect) {
    use ratatui::layout::{Constraint, Direction, Layout};

    // Split into header, content, footer
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Content
            Constraint::Length(3), // Footer
        ])
        .split(area);

    // === HEADER ===
    let header_block = Block::default()
        .title(" 📖 4Runr AI Agent OS - Command Reference ")
        .title_style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    f.render_widget(header_block, chunks[0]);

    // === CONTENT ===
    let content_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    let inner = content_block.inner(chunks[1]);
    f.render_widget(content_block, chunks[1]);

    // Build help text - single column, vertical layout
    let help_lines = vec![
        Line::from(""),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(CYBER_CYAN),
        )]),
        Line::from(vec![Span::styled(
            "  🧭 NAVIGATION COMMANDS",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(CYBER_CYAN),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    build",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Open Agent Builder (6-step wizard)",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    runs",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Open Run Manager (list, filter, sort)",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    config, settings",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Open Settings (mode, AI provider)",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(""),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(BRAND_PURPLE),
        )]),
        Line::from(vec![Span::styled(
            "  💻 LOCAL COMMANDS",
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(BRAND_PURPLE),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    quit, exit",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Exit application",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    clear",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Clear operations log",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    help",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Show this help",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    :perf",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Show performance stats",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(""),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(AMBER_WARN),
        )]),
        Line::from(vec![Span::styled(
            "  🌐 WEBSOCKET COMMANDS (requires connection)",
            Style::default().fg(AMBER_WARN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(AMBER_WARN),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    agent.list",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    List all agents",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    agent.get",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Get agent details (data: {name})",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    agent.create",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Create agent (use Agent Builder)",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    agent.delete",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Delete agent (data: {name})",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    system.status",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    Get system status",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    run.list",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    List runs (requires gateway)",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "    tool.list",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "    List available tools",
            Style::default().fg(TEXT_PRIMARY),
        )]),
        Line::from(""),
        Line::from(""),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(CYBER_CYAN),
        )]),
        Line::from(vec![Span::styled(
            "  ⌨️  SCREEN CONTROLS",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![Span::styled(
            "═══════════════════════════════════════════════════════════════",
            Style::default().fg(CYBER_CYAN),
        )]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "  Agent Builder:",
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![
            Span::styled("    Enter", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Next step  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Backspace", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Previous  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("ESC", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Cancel", Style::default().fg(TEXT_DIM)),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "  Run Manager:",
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![
            Span::styled("    ↑/↓", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Navigate  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("F", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Filter  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("S", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Sort  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("R", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Refresh", Style::default().fg(TEXT_DIM)),
        ]),
        Line::from(""),
        Line::from(vec![Span::styled(
            "  Settings:",
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::from(vec![
            Span::styled("    ↑/↓", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Navigate  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Space", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Toggle  |  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Enter", Style::default().fg(NEON_GREEN)),
            Span::styled(" = Save", Style::default().fg(TEXT_DIM)),
        ]),
        Line::from(""),
    ];

    f.render_widget(
        Paragraph::new(help_lines)
            .style(Style::default().bg(BG_PANEL))
            .wrap(Wrap { trim: false }),
        inner,
    );

    // === FOOTER ===
    let footer_text = Line::from(vec![
        Span::styled("Press ", Style::default().fg(TEXT_DIM)),
        Span::styled(
            "ESC",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" to close", Style::default().fg(TEXT_DIM)),
    ]);

    let footer_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    let footer_inner = footer_block.inner(chunks[2]);
    f.render_widget(footer_block, chunks[2]);
    f.render_widget(
        Paragraph::new(footer_text)
            .style(Style::default().bg(BG_PANEL))
            .alignment(Alignment::Center),
        footer_inner,
    );
}
