use crate::cmd::console::app::CachedDebugLogs;
use crate::cmd::console::views::common_styles;
use crate::cmd::console::widgets::formatters::truncate_message;
use ratatui::{
    layout::Rect,
    style::Style,
    symbols::border,
    widgets::{Block, HighlightSpacing, Row, Table, TableState},
    Frame,
};

pub(crate) fn render_debug_logs_placeholder(
    source: &str,
    message: &str,
    area: Rect,
    frame: &mut Frame,
) {
    let block = Block::bordered()
        .title(format!(" {} ", source))
        .border_set(border::THICK);

    let inner_area = block.inner(area);
    frame.render_widget(block, area);

    let message_width = message.len() as u16;
    let x = inner_area.x + (inner_area.width.saturating_sub(message_width)) / 2;
    let y = inner_area.y + inner_area.height / 2;

    if x < inner_area.x + inner_area.width && y < inner_area.y + inner_area.height {
        frame
            .buffer_mut()
            .set_string(x, y, message, common_styles::PLACEHOLDER_STYLE);
    }
}

pub(crate) fn render_debug_logs_panel(
    cached_logs: &CachedDebugLogs,
    source_label: &str,
    area: Rect,
    frame: &mut Frame,
    table_state: &mut TableState,
    is_focused: bool,
) {
    let border_set = if is_focused {
        border::THICK
    } else {
        border::PLAIN
    };

    let block = Block::bordered()
        .title(format!(" {} ", source_label))
        .border_set(border_set)
        .border_style(if is_focused {
            Style::default()
        } else {
            common_styles::UNFOCUSED_BORDER_STYLE
        });

    let inner_area = block.inner(area);
    frame.render_widget(block, area);

    let available_width = inner_area.width.saturating_sub(2);
    let value_width = (available_width.saturating_sub(30) as usize).max(20);

    let header = Row::new(vec!["Index", "Ago", "Value", "TID"])
        .style(common_styles::HEADER_STYLE_CYAN)
        .height(1);

    let rows: Vec<Row> = cached_logs
        .iter()
        .rev()
        .map(|entry| {
            let truncated_value = truncate_message(&entry.value, value_width);
            let thread_str = entry
                .thread_id
                .map(|t| t.to_string())
                .unwrap_or_else(|| "-".to_string());

            Row::new(vec![
                entry.index.to_string(),
                entry.ago.clone(),
                truncated_value,
                thread_str,
            ])
        })
        .collect();

    let widths = [
        ratatui::layout::Constraint::Length(6),
        ratatui::layout::Constraint::Length(10),
        ratatui::layout::Constraint::Min(20),
        ratatui::layout::Constraint::Length(8),
    ];

    let table = Table::new(rows, widths)
        .header(header)
        .row_highlight_style(common_styles::SELECTED_ROW_STYLE)
        .highlight_symbol(">> ")
        .highlight_spacing(HighlightSpacing::Always);

    frame.render_stateful_widget(table, inner_area, table_state);
}
