use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui::Frame;

use crate::tui::app::{AppState, NotificationLevel};
use crate::tui::theme;

pub fn render(f: &mut Frame, area: Rect, state: &AppState) {
    // Public WS indicator
    let (pub_icon, pub_style) = if state.ws_connected {
        ("\u{25cf}", theme::status_ok())
    } else if state.ws_reconnect_count > 0 {
        ("\u{25cb}", theme::status_warn())
    } else {
        ("\u{25cb}", theme::status_err())
    };
    let pub_label = if state.ws_connected {
        "Public WS"
    } else if state.ws_reconnect_count > 0 {
        "Reconnecting..."
    } else {
        "Connecting..."
    };

    // Private WS indicator
    let (priv_icon, priv_style, priv_label) = if !state.authenticated {
        ("\u{25cb}", theme::dim(), "No Auth")
    } else if state.private_ws_connected {
        ("\u{25cf}", theme::status_ok(), "Private WS")
    } else {
        ("\u{25cb}", theme::status_err(), "Private WS")
    };

    // Latency indicator — always visible on left side
    let latency_left: Option<Span> = state
        .ping_rtt
        .map(|rtt| rtt.as_millis() as f64)
        .or_else(|| {
            state
                .latency_history
                .back()
                .map(|s| s.network_us as f64 / 1000.0)
        })
        .map(|ms| {
            let style = if ms < 50.0 {
                theme::bid()
            } else if ms < 200.0 {
                theme::warning()
            } else {
                theme::ask()
            };
            Span::styled(format!("{ms:.0}ms"), style)
        });

    // Notification or last trade for the right side
    let right_span = if let Some(ref notif) = state.notification {
        let (icon, style) = match notif.level {
            NotificationLevel::Success => ("\u{2713} ", theme::status_ok()),
            NotificationLevel::Error => ("\u{2717} ", theme::status_err()),
            NotificationLevel::Info => ("\u{2139} ", theme::highlight()),
        };
        Some((
            Span::styled(icon, style),
            Span::styled(notif.message.clone(), style),
        ))
    } else {
        // Last trade info from recent trades
        state.recent_trades.front().and_then(|trade| {
            let price = trade
                .get("p")
                .or_else(|| trade.get("price"))
                .and_then(|v| v.as_str())?;
            let qty = trade
                .get("q")
                .or_else(|| trade.get("quantity"))
                .and_then(|v| v.as_str())?;
            let is_buyer_maker = trade
                .get("m")
                .or_else(|| trade.get("isBuyerMaker"))
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            let side = if is_buyer_maker { "sell" } else { "buy" };
            Some((
                Span::styled("", theme::dim()),
                Span::styled(format!("Last: {side} {qty} @ {price}"), theme::secondary()),
            ))
        })
    };

    // Build right-side content
    let mut right_spans: Vec<Span> = Vec::new();
    if let Some((icon_span, msg_span)) = right_span {
        if !icon_span.content.is_empty() {
            right_spans.push(icon_span);
        }
        right_spans.push(msg_span);
    }
    if !right_spans.is_empty() {
        right_spans.push(Span::styled(" ", theme::dim()));
    }

    // Build left-side spans
    let mut left_spans: Vec<Span> = vec![
        Span::styled(" ", theme::dim()),
        Span::styled(pub_icon, pub_style),
        Span::styled(format!(" {pub_label}"), theme::secondary()),
        Span::styled("  ", theme::dim()),
        Span::styled(priv_icon, priv_style),
        Span::styled(format!(" {priv_label}"), theme::secondary()),
    ];

    // Latency always shown after connection indicators
    if let Some(lat) = latency_left {
        left_spans.push(Span::styled("  ", theme::dim()));
        left_spans.push(lat);
    }

    // Optimization hint badge
    if state.optimization_hint_count > 0 {
        left_spans.push(Span::styled("  ", theme::dim()));
        left_spans.push(Span::styled(
            format!("*{} hints", state.optimization_hint_count),
            ratatui::style::Style::default().fg(theme::YELLOW),
        ));
    }

    left_spans.extend([
        Span::styled("  ", theme::dim()),
        Span::styled("?", theme::highlight()),
        Span::styled(" help  ", theme::dim()),
        Span::styled("/", theme::highlight()),
        Span::styled(" search  ", theme::dim()),
        Span::styled(":", theme::highlight()),
        Span::styled(" cmd  ", theme::dim()),
        Span::styled("q", theme::highlight()),
        Span::styled(" quit", theme::dim()),
    ]);

    let left_text_len: usize = left_spans.iter().map(|s| s.content.len()).sum();
    let right_text_len: usize = right_spans.iter().map(|s| s.content.len()).sum();
    let padding = (area.width as usize).saturating_sub(left_text_len + right_text_len);

    let mut spans = left_spans;
    spans.push(Span::styled(" ".repeat(padding), theme::dim()));

    spans.extend(right_spans);

    let line = Line::from(spans);
    let paragraph =
        Paragraph::new(line).style(ratatui::style::Style::default().bg(theme::SURFACE_ALT));
    f.render_widget(paragraph, area);
}
