// src/components/handlers/buffer_list.rs

use crate::config::colors::themes::Theme;
use crate::state::app::buffer::BufferState;
use crate::state::app::state::AppState;  // Add this import
use ratatui::{
    layout::{Alignment, Rect},
    style::Style,
    text::{Line, Span},
    widgets::Paragraph,
    Frame,
};
use unicode_width::UnicodeWidthStr;
use crate::functions::common::buffer::get_view_layer;

pub fn render_buffer_list(
    f: &mut Frame,
    area: Rect,
    theme: &Theme,
    buffer_state: &BufferState,
    app_state: &AppState,
) {
    // --- Style Definitions ---
    let active_style = Style::default()
        .fg(theme.bg)
        .bg(theme.highlight);

    let inactive_style = Style::default()
        .fg(theme.fg)
        .bg(theme.bg);

    // --- Determine Active Layer ---
    let active_layer = match buffer_state.history.get(buffer_state.active_index) {
        Some(view) => get_view_layer(view),
        None => 1,
    };

    // --- Create Spans ---
    let mut spans = Vec::new();
    let mut current_width = 0;

    let current_table_name = app_state.current_view_table_name.as_deref();

    for (original_index, view) in buffer_state.history.iter().enumerate() {
        // Filter: Only process views matching the active layer
        if get_view_layer(view) != active_layer {
            continue;
        }

        let is_active = original_index == buffer_state.active_index;
        let buffer_name = view.display_name_with_context(current_table_name);
        let buffer_text = format!(" {} ", buffer_name);
        let text_width = UnicodeWidthStr::width(buffer_text.as_str());

        // Calculate width needed for this buffer (separator + text)
        let needed_width = text_width;
        if current_width + needed_width > area.width as usize {
            break;
        }

        // Add the buffer text itself
        let text_style = if is_active { active_style } else { inactive_style };
        spans.push(Span::styled(buffer_text, text_style));
        current_width += text_width;
    }

    // --- Filler Span ---
    let remaining_width = area.width.saturating_sub(current_width as u16);
    if !spans.is_empty() || remaining_width > 0 {
        spans.push(Span::styled(
                " ".repeat(remaining_width as usize),
                inactive_style,
        ));
    }

    // --- Render ---
    let buffer_line = Line::from(spans);
    let paragraph = Paragraph::new(buffer_line).alignment(Alignment::Left);
    f.render_widget(paragraph, area);
}
