//! 左侧面板：IP 段列表（优先级低→高），并标注来源与可编辑性。

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

use crate::app::App;
use crate::net::route::RouteSource;

/// 给来源标签着色：manual 黄色（可编辑）、default 绿色、direct 灰色。
fn source_style(s: RouteSource) -> Style {
    match s {
        RouteSource::Manual => Style::default().fg(Color::Yellow),
        RouteSource::Default => Style::default().fg(Color::Green),
        RouteSource::Direct => Style::default().fg(Color::DarkGray),
    }
}

/// 收集一个 binding 里出现过的来源，按 manual/default/direct 去重排序。
fn sources_of(b: &crate::app::RouteBinding) -> Vec<RouteSource> {
    let mut v: Vec<RouteSource> = b.entries.iter().map(|e| e.source).collect();
    v.sort_by_key(|s| match s {
        RouteSource::Manual => 0,
        RouteSource::Default => 1,
        RouteSource::Direct => 2,
    });
    v.dedup();
    v
}

pub fn draw(f: &mut Frame, app: &mut App, area: Rect) {
    let title = " IP 段 (优先级低→高，[m]手动 [d]默认 [.]直连) ";

    let items: Vec<ListItem> = app
        .bindings
        .iter()
        .map(|b| {
            let cidr = b.route.to_cidr();
            // 网卡名拼接
            let devices: Vec<&str> = b
                .entries
                .iter()
                .filter_map(|e| app.services.get(e.service_idx).map(|s| s.device.as_str()))
                .collect();
            let dev_str = devices.join(",");

            // 来源标记串：如 "[m][.]"
            let src_spans: Vec<Span> = sources_of(b)
                .iter()
                .map(|&s| {
                    let ch = match s {
                        RouteSource::Manual => 'm',
                        RouteSource::Default => 'd',
                        RouteSource::Direct => '.',
                    };
                    Span::styled(format!("[{ch}]"), source_style(s))
                })
                .collect();

            let mut spans = vec![Span::styled(
                format!("{cidr:<18} "),
                Style::default().add_modifier(Modifier::BOLD),
            )];
            spans.extend(src_spans);
            spans.push(Span::raw(" "));
            spans.push(Span::styled(dev_str, Style::default().fg(Color::DarkGray)));

            ListItem::new(Line::from(spans))
        })
        .collect();

    let list = if items.is_empty() {
        List::new(vec![ListItem::new(Line::raw(
            "（暂无路由，按 a 添加手动路由）",
        ))])
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .title_alignment(Alignment::Left),
        )
        .style(Style::default().fg(Color::DarkGray))
    } else {
        List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(title)
                    .title_alignment(Alignment::Left),
            )
            .highlight_style(
                Style::default()
                    .bg(Color::DarkGray)
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("▶ ")
    };

    let mut state = ListState::default();
    if !app.bindings.is_empty() {
        state.select(Some(app.selected));
    }
    f.render_stateful_widget(list, area, &mut state);
}
