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

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

pub fn render(f: &mut Frame, area: Rect, state: &AppState) {
    let active = state.active_panel == Panel::Trades;
    let count = state.recent_trades.len();
    let info = if count > 0 {
        let scroll = state.scroll_offset(Panel::Trades);
        if scroll > 0 {
            format!("({}/{count})", scroll + 1)
        } else {
            format!("({count})")
        }
    } else {
        String::new()
    };
    let block = theme::panel_block_with_info("Recent Trades", &info, active);

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

    let mut lines = Vec::new();

    // Dynamic column widths: time fixed, price and size expand to fill
    let w = inner.width as usize;
    let time_w: usize = 8;
    let arrow_w: usize = 1;
    let gaps: usize = 6; // 3 gaps of 2 chars each
    let flexible = w.saturating_sub(time_w + arrow_w + gaps);
    let price_w = (flexible / 2).min(12);
    let size_w = flexible.saturating_sub(price_w).min(10);

    // Header
    lines.push(
        Line::from(vec![
            Span::styled(format!("{:>time_w$}", "TIME"), theme::header()),
            Span::styled("  ", theme::normal()),
            Span::styled(format!("{:>price_w$}", "PRICE"), theme::header()),
            Span::styled("  ", theme::normal()),
            Span::styled(format!("{:>size_w$}", "SIZE"), theme::header()),
            Span::styled("  ", theme::normal()),
            Span::styled(" ", theme::header()),
        ])
        .style(ratatui::style::Style::default().bg(theme::BG)),
    );

    let max_rows = (inner.height as usize).saturating_sub(1);
    let scroll = state.scroll_offset(Panel::Trades);

    for (i, trade) in state
        .recent_trades
        .iter()
        .skip(scroll)
        .take(max_rows)
        .enumerate()
    {
        let price = trade
            .get("price")
            .or_else(|| trade.get("p"))
            .and_then(|v| v.as_str())
            .unwrap_or("-");
        let qty = trade
            .get("quantity")
            .or_else(|| trade.get("q"))
            .and_then(|v| v.as_str())
            .unwrap_or("-");
        let is_buyer = trade
            .get("isBuyerMaker")
            .or_else(|| trade.get("m"))
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        // Parse timestamp
        let time_str = trade
            .get("timestamp")
            .or_else(|| trade.get("T"))
            .and_then(|v| {
                v.as_u64()
                    .or_else(|| v.as_str().and_then(|s| s.parse().ok()))
            })
            .map(format_time)
            .unwrap_or_else(|| "--:--:--".to_string());

        let (arrow, side_style) = if is_buyer {
            ("\u{25b2}", theme::bid())
        } else {
            ("\u{25bc}", theme::ask())
        };

        // Alternating row background
        let bg = if i % 2 == 0 {
            theme::BG
        } else {
            theme::SURFACE_ALT
        };
        let row_style = ratatui::style::Style::default().bg(bg);
        let price_style = side_style.bg(bg);
        let qty_style = theme::secondary().bg(bg);
        let time_style = theme::dim().bg(bg);
        let arrow_style = side_style.bg(bg);

        // Line::style() extends the background to fill the full panel width
        lines.push(
            Line::from(vec![
                Span::styled(format!("{:>time_w$}", time_str), time_style),
                Span::styled("  ", row_style),
                Span::styled(format!("{price:>price_w$}"), price_style),
                Span::styled("  ", row_style),
                Span::styled(format!("{qty:>size_w$}"), qty_style),
                Span::styled("  ", row_style),
                Span::styled(arrow, arrow_style),
            ])
            .style(row_style),
        );
    }

    // Fill remaining empty rows with alternating background
    let data_rows = state
        .recent_trades
        .iter()
        .skip(scroll)
        .take(max_rows)
        .count();
    for i in data_rows..max_rows {
        let bg = if i % 2 == 0 {
            theme::BG
        } else {
            theme::SURFACE_ALT
        };
        lines.push(Line::from("").style(ratatui::style::Style::default().bg(bg)));
    }

    if state.recent_trades.is_empty() {
        lines.push(Line::from(Span::styled(
            "  Waiting for trades...",
            theme::dim(),
        )));
    }

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

fn format_time(ts_ms: u64) -> String {
    let secs = (ts_ms / 1000) % 86400;
    let h = secs / 3600;
    let m = (secs % 3600) / 60;
    let s = secs % 60;
    format!("{h:02}:{m:02}:{s:02}")
}
