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

use crate::tui::app::AppState;
use crate::tui::theme;

pub fn render(f: &mut Frame, area: Rect, state: &AppState) {
    let popup = centered_rect(40, 60, area);
    f.render_widget(Clear, popup);

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

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

    let mut lines = Vec::new();

    // Input field
    let input_display = format!("  > {}\u{2588}", state.symbol_search_input);
    lines.push(Line::from(Span::styled(input_display, theme::normal())));
    lines.push(Line::from(""));

    // Category tabs: [ Spot ]  Perps  or  Spot  [ Perps ]
    let spot_style = if state.symbol_search_category == 0 {
        ratatui::style::Style::default()
            .fg(theme::BG)
            .bg(theme::ACCENT)
            .add_modifier(Modifier::BOLD)
    } else {
        theme::dim()
    };
    let perps_style = if state.symbol_search_category == 1 {
        ratatui::style::Style::default()
            .fg(theme::BG)
            .bg(theme::ACCENT)
            .add_modifier(Modifier::BOLD)
    } else {
        theme::dim()
    };
    lines.push(Line::from(vec![
        Span::styled("  ", theme::dim()),
        Span::styled(" Spot ", spot_style),
        Span::styled("  ", theme::dim()),
        Span::styled(" Perps ", perps_style),
        Span::styled("      Tab to switch", theme::dim()),
    ]));
    lines.push(Line::from(""));

    let results = &state.symbol_search_results;

    if results.is_empty() && !state.symbol_search_input.is_empty() {
        lines.push(Line::from(Span::styled(
            "  Nothing here... try the other tab?",
            theme::dim(),
        )));
    } else if results.is_empty() {
        lines.push(Line::from(Span::styled(
            "  No markets loaded yet",
            theme::dim(),
        )));
    } else {
        // Visible window with scroll following selection
        let visible_count = (inner.height as usize).saturating_sub(6);
        let selected = state.symbol_search_selected;

        let scroll_offset = if selected >= visible_count {
            selected - visible_count + 1
        } else {
            0
        };

        for (i, symbol) in results
            .iter()
            .skip(scroll_offset)
            .take(visible_count)
            .enumerate()
        {
            let actual_index = scroll_offset + i;
            let is_selected = actual_index == selected;
            let style = if is_selected {
                ratatui::style::Style::default()
                    .fg(theme::BG)
                    .bg(theme::ACCENT)
            } else {
                theme::secondary()
            };
            let vol_style = if is_selected { style } else { theme::dim() };

            // Look up 24h volume from tickers
            let vol_str = state
                .all_tickers
                .get(symbol)
                .and_then(|t| {
                    t.get("volume").and_then(|v| {
                        v.as_str()
                            .and_then(|s| s.parse::<f64>().ok())
                            .or(v.as_f64())
                    })
                })
                .map(|v| format!("  V:{}", format_compact(v)))
                .unwrap_or_default();

            lines.push(Line::from(vec![
                Span::styled(format!("  {symbol:<20}"), style),
                Span::styled(vol_str, vol_style),
            ]));
        }
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  \u{2191}\u{2193} navigate  Tab spot/perps  Enter select  Esc cancel",
        theme::dim(),
    )));

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

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]
}

fn format_compact(val: f64) -> String {
    if val >= 1_000_000.0 {
        format!("{:.1}M", val / 1_000_000.0)
    } else if val >= 1_000.0 {
        format!("{:.1}K", val / 1_000.0)
    } else {
        format!("{:.1}", val)
    }
}
