use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Clear, Paragraph};
use ratatui::Frame;

use crate::tui::theme;

pub fn render(f: &mut Frame, area: Rect) {
    let popup = centered_rect(55, 90, area);
    f.render_widget(Clear, popup);

    let block = Block::default()
        .title(" Keys ")
        .title_style(theme::title())
        .borders(Borders::ALL)
        .border_style(ratatui::style::Style::default().fg(theme::BORDER_COLOR))
        .style(ratatui::style::Style::default().bg(theme::SURFACE));

    let inner = block.inner(popup);
    f.render_widget(block, popup);

    let lines = vec![
        Line::from(""),
        section_header("Navigation"),
        shortcut("Tab", "Next panel"),
        shortcut("Shift+Tab", "Previous panel"),
        shortcut("1-6", "Jump to panel"),
        Line::from(""),
        section_header("Data"),
        shortcut("j / \u{2193}", "Scroll down"),
        shortcut("k / \u{2191}", "Scroll up"),
        shortcut("g", "Jump to top"),
        shortcut("G", "Jump to bottom"),
        shortcut("[ / ]", "Chart interval"),
        Line::from(""),
        section_header("Trading"),
        shortcut("o", "Open order form"),
        shortcut("d", "Cancel selected order"),
        shortcut("x", "Close selected position"),
        Line::from(""),
        section_header("System"),
        shortcut("/", "Symbol search"),
        shortcut(":", "Command bar"),
        shortcut("?", "Toggle this help"),
        shortcut("P", "Toggle PnL sparkline"),
        shortcut("C", "Toggle collateral breakdown"),
        shortcut("L", "Toggle latency display"),
        shortcut("q / Ctrl-C", "Quit (touch grass)"),
        Line::from(""),
        section_header("Commands (:)"),
        shortcut(":symbol SYM", "Switch symbol"),
        shortcut(":switch SYM", "Switch symbol (alias)"),
        shortcut(":interval 5m", "Chart interval"),
        shortcut(":panel orders", "Jump to panel"),
        shortcut(":order", "Open order form"),
        shortcut(":cancel", "Cancel order"),
        shortcut(":close", "Close position"),
        shortcut(":refresh", "Force data refresh"),
        shortcut(":q", "Quit"),
        Line::from(""),
        section_header("Keybindings (:)"),
        shortcut(":bind K ACT", "Bind key to action"),
        shortcut(":unbind K", "Remove key binding"),
        shortcut(":unbind all", "Reset all bindings"),
        shortcut(":bind list", "Show all bindings"),
        Line::from(Span::styled(
            "  Unrecognized \u{2192} runs bpx CLI",
            theme::dim(),
        )),
        Line::from(""),
        section_header("Trading Commands (:)"),
        shortcut("buy/sell <n>", "Market order (units)"),
        shortcut("buy/sell <n>$", "Market order ($ worth)"),
        shortcut("buy/sell <n>%", "% of max order size"),
        shortcut("... at <price>", "Limit order"),
        shortcut("... at +2 / -1%", "Offset from mark"),
        shortcut("... best", "Limit at best bid/ask"),
        shortcut("... reduce", "Reduce-only flag"),
        shortcut(":close [%]", "Close position (or %)"),
        shortcut(":nuke orders", "Cancel all orders"),
        shortcut(":nuke positions", "Close all positions"),
        shortcut(":nuke all", "Cancel + close everything"),
        shortcut(":flatten", "Alias for nuke all"),
        Line::from(""),
        section_header("Analytics (:)"),
        shortcut(":scenario", "What-if scenario tester"),
        shortcut(":risk", "Risk summary + stress tests"),
        shortcut(":strategy", "list/run saved strategies"),
        shortcut(":stats", "7-day trading analytics"),
        shortcut(":optimize", "Collateral optimization (CLI)"),
        Line::from(""),
        Line::from(Span::styled("  you're doing great, anon", theme::dim())),
    ];

    let paragraph = Paragraph::new(lines);
    f.render_widget(paragraph, inner);
}

fn section_header(name: &str) -> Line<'_> {
    Line::from(Span::styled(
        format!("  \u{2500}\u{2500} {name} \u{2500}\u{2500}"),
        theme::title(),
    ))
}

fn shortcut<'a>(key: &'a str, desc: &'a str) -> Line<'a> {
    Line::from(vec![
        Span::styled(format!("  {key:>14}"), theme::highlight()),
        Span::styled(format!("  {desc}"), theme::normal()),
    ])
}

fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
    let popup_layout = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage((100 - percent_y) / 2),
            Constraint::Percentage(percent_y),
            Constraint::Percentage((100 - percent_y) / 2),
        ])
        .split(r);

    Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage((100 - percent_x) / 2),
            Constraint::Percentage(percent_x),
            Constraint::Percentage((100 - percent_x) / 2),
        ])
        .split(popup_layout[1])[1]
}
