use ratatui::layout::Rect;
use ratatui::text::Line;
use ratatui::widgets::{Block, Borders, Tabs};
use ratatui::Frame;

use crate::theme::theme;

/// The tabs available in the application
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tab {
    Plugins,
    Paths,
    Config,
    Log,
}

impl Tab {
    pub fn all() -> &'static [Tab] {
        &[Tab::Plugins, Tab::Paths, Tab::Config, Tab::Log]
    }

    pub fn title(&self) -> &str {
        match self {
            Tab::Plugins => " Plugins ",
            Tab::Paths => " Paths ",
            Tab::Config => " Config ",
            Tab::Log => " Log ",
        }
    }

    pub fn index(&self) -> usize {
        match self {
            Tab::Plugins => 0,
            Tab::Paths => 1,
            Tab::Config => 2,
            Tab::Log => 3,
        }
    }

    pub fn from_index(index: usize) -> Self {
        match index % 4 {
            0 => Tab::Plugins,
            1 => Tab::Paths,
            2 => Tab::Config,
            3 => Tab::Log,
            _ => unreachable!(),
        }
    }

    pub fn next(&self) -> Self {
        Self::from_index(self.index() + 1)
    }

    pub fn prev(&self) -> Self {
        Self::from_index((self.index() + 3) % 4)
    }
}

/// Render the tab bar
pub fn render_tab_bar(frame: &mut Frame, area: Rect, active_tab: Tab) {
    let t = theme();
    let titles: Vec<Line> = Tab::all()
        .iter()
        .map(|tab| {
            let style = if *tab == active_tab {
                t.tab_active
            } else {
                t.tab_inactive
            };
            Line::styled(tab.title(), style)
        })
        .collect();

    let tabs = Tabs::new(titles)
        .block(
            Block::default()
                .borders(Borders::BOTTOM)
                .border_style(t.border)
                .title(" yabridge-tui ")
                .title_style(t.title),
        )
        .select(active_tab.index())
        .divider("│")
        .padding(" ", " ");

    frame.render_widget(tabs, area);
}
