use ratatui::{
    Frame,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, ListState},
};

use crate::{state::App, theme::Theme, ui::centered_rect};

pub fn render(f: &mut Frame, app: &App, theme: &Theme) {
    let area = centered_rect(80, 70, f.area());
    f.render_widget(Clear, area);

    let items: Vec<ListItem> = if app.comments.is_empty() {
        vec![ListItem::new(Line::from(Span::styled(
            "(no comments)",
            Style::default().fg(theme.dim_fg),
        )))]
    } else {
        app.comments
            .iter()
            .map(|c| {
                ListItem::new(Line::from(vec![
                    Span::styled(
                        c.location(),
                        Style::default()
                            .fg(theme.dialog_location_fg)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::raw("  "),
                    Span::styled(c.body.clone(), Style::default().fg(theme.dialog_body_fg)),
                ]))
            })
            .collect()
    };

    let title = format!(" Comments ({}) ", app.comments.len());
    let list = List::new(items)
        .style(Style::default().bg(theme.bg_alt))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(Span::styled(
                    title,
                    Style::default()
                        .fg(theme.bg)
                        .bg(theme.shuire)
                        .add_modifier(Modifier::BOLD),
                ))
                .border_style(Style::default().fg(theme.shuire).bg(theme.bg_alt))
                .style(Style::default().bg(theme.bg_alt)),
        )
        .highlight_style(
            Style::default()
                .bg(theme.cursor_bg)
                .add_modifier(Modifier::BOLD),
        );

    let mut state = ListState::default();
    if !app.comments.is_empty() {
        state.select(Some(app.comments_list_cursor.min(app.comments.len() - 1)));
    }
    f.render_stateful_widget(list, area, &mut state);
}
