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

use crate::model::Model;
use crate::ui::app::AppMode;
use crate::ui::panel::PanelContent;

pub struct FormulaContent<'a> {
    pub model: &'a Model,
    pub mode: &'a AppMode,
}

impl<'a> FormulaContent<'a> {
    pub fn new(model: &'a Model, mode: &'a AppMode) -> Self {
        Self { model, mode }
    }
}

impl PanelContent for FormulaContent<'_> {
    fn is_active(&self, mode: &AppMode) -> bool {
        matches!(mode, AppMode::FormulaPanel | AppMode::FormulaEdit { .. })
    }

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

    fn title(&self) -> &str {
        " Formulas [n]ew [d]elete "
    }

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

    fn empty_message(&self) -> &str {
        "(no formulas — press 'n' to add)"
    }

    fn render_item(&self, index: usize, is_selected: bool, inner: Rect, buf: &mut Buffer) {
        let formula = &self.model.formulas()[index];
        let style = if is_selected {
            Style::default()
                .fg(Color::Black)
                .bg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Green)
        };
        let text = format!("  {}", formula.raw);
        let truncated = if text.len() > inner.width as usize {
            format!("{}…", &text[..inner.width as usize - 1])
        } else {
            text
        };
        buf.set_string(inner.x, inner.y + index as u16, &truncated, style);
    }

    fn footer_height(&self) -> u16 {
        if matches!(self.mode, AppMode::FormulaEdit { .. }) {
            1
        } else {
            0
        }
    }

    fn render_footer(&self, inner: Rect, buf: &mut Buffer) {
        if matches!(self.mode, AppMode::FormulaEdit { .. }) {
            let y = inner.y + inner.height.saturating_sub(1);
            buf.set_string(
                inner.x,
                y,
                "┄ Enter formula (Name = expr)",
                Style::default().fg(Color::Yellow),
            );
        }
    }
}
