use lv_tui::prelude::*;
use lv_tui::widgets::*;
use lv_tui::widgets::{ColumnWidth, Table, TableCell, TableColumn, TableRow};

struct App { content: Column }

impl App {
    fn new() -> Self {
        let table = Table::new()
            .columns(vec![
                TableColumn { title: Text::from("文件"), width: ColumnWidth::Flex(2), align: TextAlign::Left },
                TableColumn { title: Text::from("类型"), width: ColumnWidth::Flex(1), align: TextAlign::Left },
                TableColumn { title: Text::from("大小"), width: ColumnWidth::Fixed(10), align: TextAlign::Right },
            ])
            .rows(vec![
                TableRow::new(vec!["README.md", "file", "1.2KB"]),
                TableRow::new(vec!["src/main.rs", "file", "3.4KB"]),
                TableRow::new(vec![
                    TableCell { content: Text::from("Cargo.toml"), style: Some(Style::default().fg(Color::Cyan)) },
                    TableCell { content: Text::from("file"), style: None },
                    TableCell { content: Text::from("0.1KB"), style: None },
                ]),
                TableRow::new(vec!["LICENSE", "file", "1.0KB"]),
            ])
            .footer(TableRow::new(vec![
                TableCell { content: Text::from("4 files"), style: Some(Style::default().bold()) },
                TableCell { content: Text::from(""), style: None },
                TableCell { content: Text::from("5.8KB"), style: Some(Style::default().bold()) },
            ]))
            .header_style(Style::default().bold().underline())
            .select_style(Style::default().bg(Color::White).fg(Color::Black));

        Self {
            content: Column::new()
                .child(Label::new("Table v2 Demo").style(Style::default().bold()))
                .child(Label::new(""))
                .child(Block::new(table).border(Border::Rounded).padding(1)
                    .title("File Browser").title_alignment(TextAlign::Center))
                .child(Label::new(""))
                .child(Label::new("Flex cols + footer + per-cell style  ↑↓ nav  q quit").style(Style::default().fg(Color::Gray))),
        }
    }
}

impl Component for App {
    fn render(&self, cx: &mut RenderCx) { self.content.render(cx); }
    fn event(&mut self, e: &Event, cx: &mut EventCx) {
        if e.is_key(Key::Char('q')) { cx.quit(); return; }
        self.content.event(e, cx);
    }
    fn layout(&mut self, r: lv_tui::geom::Rect, cx: &mut lv_tui::component::LayoutCx) { self.content.layout(r, cx); }
    fn measure(&self, c: lv_tui::layout::Constraint, _cx: &mut lv_tui::component::MeasureCx) -> lv_tui::geom::Size {
        lv_tui::geom::Size { width: c.max.width, height: c.max.height }
    }
    fn focusable(&self) -> bool { false }
}

fn main() -> lv_tui::Result<()> {
    lv_tui::app::App::new(App::new()).run()
}
