use crate::client::tui::app::{App, Focus};
use ratatui::{
    Frame,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState},
};

pub fn render(frame: &mut Frame, area: Rect, app: &App) {
    let items = app.sessions.iter().enumerate().map(|(index, session)| {
        let selected = app.focus == Focus::Sessions && index == app.selected_session;
        let current = app.current_session_id.as_ref() == Some(&session.session_id);
        let marker = if current { "●" } else { " " };
        let archived = if session.archived_at.is_some() {
            " 归档"
        } else {
            ""
        };
        let style = if selected {
            Style::default().fg(Color::Black).bg(Color::Cyan)
        } else if current {
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        ListItem::new(vec![
            Line::from(vec![
                Span::raw(format!("{marker} ")),
                Span::styled(session.title.clone(), style),
            ]),
            Line::from(Span::styled(
                format!("  {} 条{archived}", session.message_count),
                Style::default().fg(Color::DarkGray),
            )),
        ])
        .style(style)
    });
    let mode = if app.show_archived {
        "全部"
    } else {
        "活跃"
    };
    let border = if app.focus == Focus::Sessions {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default()
    };
    let list = List::new(items).block(
        Block::default()
            .title(format!(" 会话 · {mode} "))
            .borders(Borders::ALL)
            .border_style(border),
    );
    let selected = (!app.sessions.is_empty()).then_some(app.selected_session);
    let mut state = ListState::default().with_selected(selected);
    frame.render_stateful_widget(list, area, &mut state);
}
