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

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

const SPARK_CHARS: &[char] = &['▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];

pub fn render(f: &mut Frame, area: Rect, state: &AppState) {
    let block = theme::panel_block("PnL", false);
    let inner = block.inner(area);
    f.render_widget(block, area);

    if state.pnl_history.is_empty() {
        let msg = Paragraph::new(Span::styled(" No PnL data yet", theme::dim()));
        f.render_widget(msg, inner);
        return;
    }

    let sparkline = build_sparkline(&state.pnl_history);
    let current_pnl = state.pnl_history.last().copied().unwrap_or(0.0);
    let pnl_color = if current_pnl >= 0.0 {
        theme::GREEN
    } else {
        theme::RED
    };

    let line = Line::from(vec![
        Span::styled(" ", theme::dim()),
        Span::styled(
            sparkline,
            ratatui::style::Style::default().fg(theme::ACCENT),
        ),
        Span::styled(
            format!("  {:+.2}", current_pnl),
            ratatui::style::Style::default().fg(pnl_color),
        ),
    ]);

    let paragraph = Paragraph::new(vec![line]);
    f.render_widget(paragraph, inner);
}

fn build_sparkline(values: &[f64]) -> String {
    if values.is_empty() {
        return String::new();
    }
    let min = values.iter().cloned().fold(f64::MAX, f64::min);
    let max = values.iter().cloned().fold(f64::MIN, f64::max);
    let range = max - min;

    values
        .iter()
        .map(|v| {
            if range == 0.0 {
                SPARK_CHARS[3]
            } else {
                let normalized = ((v - min) / range * 7.0).round() as usize;
                SPARK_CHARS[normalized.min(7)]
            }
        })
        .collect()
}
