use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
};

use crate::ui::app::AppMode;
use crate::ui::panel::PanelContent;
use crate::view::Axis;
use crate::workbook::Workbook;

pub struct ViewContent<'a> {
    view_names: Vec<String>,
    active_view: String,
    workbook: &'a Workbook,
}

impl<'a> ViewContent<'a> {
    pub fn new(workbook: &'a Workbook) -> Self {
        let view_names: Vec<String> = workbook.views.keys().cloned().collect();
        let active_view = workbook.active_view.clone();
        Self {
            view_names,
            active_view,
            workbook,
        }
    }

    /// Build a short axis summary for a view, e.g. "R:Region C:Product P:Time"
    fn axis_summary(&self, view_name: &str) -> String {
        let Some(view) = self.workbook.views.get(view_name) else {
            return String::new();
        };
        let mut parts = Vec::new();
        for axis in [Axis::Row, Axis::Column, Axis::Page] {
            let cats = view.categories_on(axis);
            // Filter out virtual categories
            let cats: Vec<&str> = cats.into_iter().filter(|c| !c.starts_with('_')).collect();
            if !cats.is_empty() {
                let prefix = match axis {
                    Axis::Row => "R",
                    Axis::Column => "C",
                    Axis::Page => "P",
                    Axis::None => "",
                };
                parts.push(format!("{}:{}", prefix, cats.join(",")));
            }
        }
        parts.join(" ")
    }
}

impl PanelContent for ViewContent<'_> {
    fn is_active(&self, mode: &AppMode) -> bool {
        matches!(mode, AppMode::ViewPanel)
    }

    fn active_color(&self) -> Color {
        Color::Blue
    }

    fn title(&self) -> &str {
        " Views "
    }

    fn item_count(&self) -> usize {
        self.view_names.len()
    }

    fn empty_message(&self) -> &str {
        "(no views)"
    }

    fn render_item(&self, index: usize, is_selected: bool, inner: Rect, buf: &mut Buffer) {
        let view_name = &self.view_names[index];
        let is_active_view = view_name == &self.active_view;

        let style = if is_selected {
            Style::default()
                .fg(Color::Black)
                .bg(Color::Blue)
                .add_modifier(Modifier::BOLD)
        } else if is_active_view {
            Style::default()
                .fg(Color::Blue)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };

        let prefix = if is_active_view { "▶ " } else { "  " };
        let name_text = format!("{prefix}{view_name}");
        let y = inner.y + index as u16;
        buf.set_string(inner.x, y, &name_text, style);

        // Axis summary after the name, in dim text
        let summary = self.axis_summary(view_name);
        if !summary.is_empty() {
            let summary_x = inner.x + name_text.len() as u16 + 1;
            if summary_x < inner.x + inner.width {
                let summary_style = if is_selected {
                    style
                } else {
                    Style::default().fg(Color::DarkGray)
                };
                buf.set_string(summary_x, y, &summary, summary_style);
            }
        }
    }
}
