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

use crate::tui::app::CommandOutput;
use crate::tui::theme;

/// Renders command output as a bottom drawer that keeps trading data visible.
/// Height adapts to content: short output gets a compact drawer, long output gets ~35%.
pub fn render(f: &mut Frame, area: Rect, output: &CommandOutput) {
    let line_count = output.output.lines().count();
    let drawer = bottom_drawer(area, line_count);
    f.render_widget(Clear, drawer);

    let title = format!(" :{} ", output.command);
    let title_style = if output.success {
        theme::title()
    } else {
        theme::status_err()
    };

    let block = Block::default()
        .title(title)
        .title_style(title_style)
        .borders(Borders::TOP)
        .border_style(ratatui::style::Style::default().fg(theme::BORDER_FOCUS))
        .style(ratatui::style::Style::default().bg(theme::SURFACE));

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

    // Split inner area: content + footer hint line
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Min(1), Constraint::Length(1)])
        .split(inner);

    // Output content with scrolling
    let lines: Vec<Line> = output
        .output
        .lines()
        .map(|l| Line::from(Span::styled(l.to_string(), theme::normal())))
        .collect();

    let paragraph = Paragraph::new(lines)
        .scroll((output.scroll_offset as u16, 0))
        .wrap(Wrap { trim: false });
    f.render_widget(paragraph, chunks[0]);

    // Footer hints
    let footer = Line::from(vec![
        Span::styled("  j/k", theme::highlight()),
        Span::styled(" scroll  ", theme::dim()),
        Span::styled("q/Esc", theme::highlight()),
        Span::styled(" close  ", theme::dim()),
        Span::styled(":", theme::highlight()),
        Span::styled(" new cmd", theme::dim()),
    ]);
    let footer_para = Paragraph::new(footer);
    f.render_widget(footer_para, chunks[1]);
}

/// Bottom-anchored drawer. Height adapts: compact for short output, up to 35% for long.
fn bottom_drawer(area: Rect, line_count: usize) -> Rect {
    // Content lines + 2 for border/title + 1 for footer
    let content_h = (line_count as u16).saturating_add(3);
    let max_h = (area.height * 35 / 100).max(6);
    let h = content_h.clamp(6, max_h);
    Rect {
        x: area.x,
        y: area.y + area.height - h,
        width: area.width,
        height: h,
    }
}
