use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Block, Borders, Clear, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState,
};
use ratatui::Frame;

use crate::components::ui_utils;
use crate::theme::{theme, theme_name};

/// Render the help overlay (scrollable)
pub fn render_help(frame: &mut Frame, area: Rect, scroll: u16) {
    let t = theme();

    let popup_area = ui_utils::centered_rect(70, 80, area);
    frame.render_widget(Clear, popup_area);

    let help_lines = vec![
        Line::from(""),
        Line::from(Span::styled("  Navigation", t.title)),
        Line::from(""),
        help_line("  Tab / Shift+Tab", "Switch between tabs"),
        help_line("  h l / Left Right", "Switch between tabs"),
        help_line("  1 2 3 4", "Jump to tab directly"),
        help_line("  j / Down", "Move selection down"),
        help_line("  k / Up", "Move selection up"),
        help_line("  d / PageDown", "Jump 10 items down"),
        help_line("  u / PageUp", "Jump 10 items up"),
        help_line("  g / Home", "Go to first item"),
        help_line("  G / End", "Go to last item"),
        Line::from(""),
        Line::from(Span::styled("  Plugins Tab", t.title)),
        Line::from(""),
        help_line("  f / /", "Filter plugins (interactive search)"),
        help_line("    Enter", "Keep filter, exit input"),
        help_line("    Esc", "Clear filter, exit input"),
        help_line("  t", "Cycle type filter (All/VST2/VST3/CLAP)"),
        help_line("  o", "Cycle sort (name/type/status)"),
        help_line("  s", "Sync plugins (yabridgectl sync --verbose)"),
        help_line("  S", "Force sync (yabridgectl sync --force)"),
        help_line("  p", "Sync with prune (yabridgectl sync --prune)"),
        help_line("  r", "Refresh plugin list"),
        Line::from(""),
        Line::from(Span::styled("  Paths Tab", t.title)),
        Line::from(""),
        help_line("  f / /", "Filter paths"),
        help_line("  a", "Add a plugin directory"),
        help_line("  d / Delete", "Remove selected directory"),
        Line::from(""),
        Line::from(Span::styled("  File Browser (Paths > a)", t.title)),
        Line::from(""),
        help_line("  Enter", "Select current directory"),
        help_line("  l / Right", "Open selected directory"),
        help_line("  h / Left / Bksp", "Go to parent directory"),
        help_line("  f / /", "Filter entries"),
        help_line("  Esc", "Clear filter / Close browser"),
        help_line("  q", "Close browser"),
        Line::from(""),
        Line::from(Span::styled("  Config Tab (Browse)", t.title)),
        Line::from(""),
        help_line("  Enter", "Edit selected rule (enter edit mode)"),
        help_line("  e", "Edit rule pattern (glob)"),
        help_line("  a", "Add a new config rule"),
        help_line("  d / Delete", "Delete selected rule"),
        help_line("  w", "Save yabridge.toml"),
        help_line("  r", "Reload config from disk"),
        Line::from(""),
        Line::from(Span::styled("  Config Tab (Edit Mode)", t.title)),
        Line::from(""),
        help_line("  j / k", "Navigate between fields"),
        help_line("  g / G", "First / last field"),
        help_line("  Space / Enter", "Cycle bool (unset/yes/no) / edit value"),
        help_line("  x", "Clear field (reset to default)"),
        help_line("  w", "Save yabridge.toml"),
        help_line("  Esc", "Back to browse mode"),
        Line::from(""),
        Line::from(Span::styled("  Log Tab", t.title)),
        Line::from(""),
        help_line("  j / k", "Scroll up / down"),
        help_line("  d / u", "Scroll page down / up"),
        help_line("  f / /", "Filter log lines"),
        help_line("  c", "Clear log"),
        help_line("  G", "Scroll to bottom (auto-scroll on)"),
        help_line("  g", "Scroll to top"),
        Line::from(""),
        Line::from(Span::styled("  General", t.title)),
        Line::from(""),
        help_line_dynamic(
            "  T",
            &format!("Cycle color theme (current: {})", theme_name().display()),
            t,
        ),
        help_line("  ?", "Toggle this help"),
        help_line("  q / Esc", "Quit (or close popup)"),
        help_line("  Ctrl+C", "Force quit"),
        Line::from(""),
    ];

    let total_lines = help_lines.len() as u16;
    let visible_rows = popup_area.height.saturating_sub(2); // border
    let max_scroll = total_lines.saturating_sub(visible_rows);
    let effective_scroll = scroll.min(max_scroll);

    let help = Paragraph::new(help_lines)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(t.popup_border)
                .title(" Help (j/k scroll, q close) ")
                .title_style(t.popup_title),
        )
        .scroll((effective_scroll, 0));

    frame.render_widget(help, popup_area);

    // Scrollbar
    if total_lines > visible_rows {
        let scrollbar = Scrollbar::new(ScrollbarOrientation::VerticalRight)
            .begin_symbol(Some("↑"))
            .end_symbol(Some("↓"));
        let mut scrollbar_state =
            ScrollbarState::new(max_scroll as usize).position(effective_scroll as usize);
        frame.render_stateful_widget(scrollbar, popup_area, &mut scrollbar_state);
    }
}

fn help_line<'a>(key: &'a str, desc: &'a str) -> Line<'a> {
    let t = theme();
    Line::from(vec![
        Span::styled(format!("{:<22}", key), t.status_bar_key),
        Span::styled(desc, t.log_info),
    ])
}

fn help_line_dynamic(key: &str, desc: &str, t: &'static crate::theme::Theme) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{:<22}", key), t.status_bar_key),
        Span::styled(desc.to_string(), t.log_info),
    ])
}
