//! 右侧面板：选中 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, Paragraph};
use ratatui::Frame;

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

/// 来源标签着色（与 sidebar 一致）。
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),
    }
}

fn source_full_label(s: RouteSource) -> &'static str {
    match s {
        RouteSource::Manual => "manual (手动附加，可删除)",
        RouteSource::Default => "default (默认路由，只读)",
        RouteSource::Direct => "direct (直连网段，只读)",
    }
}

pub fn draw(f: &mut Frame, app: &mut App, area: Rect) {
    let binding = app.bindings.get(app.selected);

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" 绑定详情 ")
        .title_alignment(Alignment::Left);

    match binding {
        None => {
            let p = Paragraph::new("（未选择路由）")
                .style(Style::default().fg(Color::DarkGray))
                .alignment(Alignment::Center)
                .block(block);
            f.render_widget(p, area);
        }
        Some(b) => {
            let header = Line::from(vec![
                Span::styled(" 选中: ", Style::default().fg(Color::Gray)),
                Span::styled(
                    b.route.to_cidr(),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
            ]);

            let sub = Line::from(Span::styled(
                " 命中详情（←→ 切换，仅 manual 可按 d 删除）:",
                Style::default().fg(Color::DarkGray),
            ));

            let blank = Line::raw("");

            let items: Vec<ListItem> = b
                .entries
                .iter()
                .enumerate()
                .map(|(_pos, e)| {
                    let svc = match app.services.get(e.service_idx) {
                        Some(s) => s,
                        None => return ListItem::new(Line::raw("  <未知服务>")),
                    };
                    let enabled_marker = if svc.enabled { "" } else { " [禁用]" };
                    let order_str = if svc.enabled {
                        format!("优先级 {}", svc.order)
                    } else {
                        "已禁用".to_string()
                    };
                    let gw_str = match e.gateway {
                        Some(g) => format!("via {g}"),
                        None => "on-link".to_string(),
                    };

                    ListItem::new(Line::from(vec![
                        Span::styled(
                            format!("  {:<6} ", svc.device),
                            Style::default()
                                .fg(Color::Cyan)
                                .add_modifier(Modifier::BOLD),
                        ),
                        Span::styled(
                            format!("[{:>7}] ", e.source.label()),
                            source_style(e.source),
                        ),
                        Span::styled(
                            format!("{}({})", svc.hardware_port, svc.name),
                            Style::default().fg(Color::Gray),
                        ),
                        Span::raw("  "),
                        Span::styled(gw_str, Style::default().fg(Color::Magenta)),
                        Span::raw("  "),
                        Span::styled(order_str, Style::default().fg(Color::DarkGray)),
                        Span::styled(
                            enabled_marker.to_string(),
                            Style::default().fg(Color::Red),
                        ),
                    ]))
                })
                .collect();

            // 来源说明行（只展示当前选中 entry）
            let cur_source = b
                .entries
                .get(app.detail_selected)
                .map(|e| e.source);
            let source_line = match cur_source {
                Some(s) => Line::from(vec![
                    Span::raw("  └ "),
                    Span::styled(source_full_label(s), source_style(s)),
                ]),
                None => Line::raw(""),
            };

            let mut all: Vec<ListItem> = vec![
                ListItem::new(header),
                ListItem::new(sub),
                ListItem::new(blank),
            ];
            all.extend(items);
            all.push(ListItem::new(Line::raw("")));
            all.push(ListItem::new(source_line));

            let list = List::new(all)
                .block(block)
                .highlight_style(
                    Style::default()
                        .bg(Color::DarkGray)
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                )
                .highlight_symbol("▶ ");

            // state 选中：头部占了 3 行 + 末尾 2 行说明不参与选中，
            // 但 state.select 指向的是"列表项"序号，我们让 detail_selected
            // 直接对应 entries 在 all 中的位置（all[3..] 是 entries）。
            let mut state = ListState::default();
            if app.detail_selected < b.entries.len() {
                state.select(Some(app.detail_selected + 3));
            }
            f.render_stateful_widget(list, area, &mut state);
        }
    }
}
