use ratatui::layout::Rect;
use ratatui::symbols::Marker;
use ratatui::widgets::{Axis, Chart, Dataset, GraphType};
use ratatui::Frame;

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

pub fn render(f: &mut Frame, area: Rect, state: &AppState) {
    let active = state.active_panel == Panel::Chart;
    let interval = KLINE_INTERVALS[state.kline_interval];
    let title = format!("Chart [{interval}]  [ ] switch");
    let block = theme::panel_block(&title, active);

    if state.kline_history.is_empty() {
        let inner = block.inner(area);
        f.render_widget(block, area);
        let msg = ratatui::widgets::Paragraph::new(ratatui::text::Span::styled(
            "  Waiting for price data...",
            theme::dim(),
        ));
        f.render_widget(msg, inner);
        return;
    }

    let prices: Vec<f64> = state.kline_history.iter().copied().collect();
    let min_price = prices.iter().cloned().fold(f64::MAX, f64::min);
    let max_price = prices.iter().cloned().fold(f64::MIN, f64::max);
    let padding = (max_price - min_price).max(0.01) * 0.05;

    let data_points: Vec<(f64, f64)> = prices
        .iter()
        .enumerate()
        .map(|(i, p)| (i as f64, *p))
        .collect();

    let dataset = Dataset::default()
        .marker(Marker::Braille)
        .graph_type(GraphType::Line)
        .style(ratatui::style::Style::default().fg(theme::ACCENT))
        .data(&data_points);

    let y_low = min_price - padding;
    let y_high = max_price + padding;
    let x_max = (prices.len().max(1) - 1) as f64;

    let chart = Chart::new(vec![dataset])
        .block(block)
        .x_axis(Axis::default().bounds([0.0, x_max]))
        .y_axis(Axis::default().bounds([y_low, y_high]).labels(vec![
            ratatui::text::Span::styled(format!("{min_price:.2}"), theme::dim()),
            ratatui::text::Span::styled(format!("{max_price:.2}"), theme::dim()),
        ]));

    f.render_widget(chart, area);
}
