//! 弹窗：添加路由 / 删除确认 / 帮助 / 错误。

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

use crate::app::{AddFocus, App, Mode};

/// 居中放置一个给定尺寸的弹窗区域。
fn centered_rect(width: u16, height: u16, area: Rect) -> Rect {
    let v = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length((area.height.saturating_sub(height)) / 2),
            Constraint::Length(height),
            Constraint::Min(0),
        ])
        .split(area);
    let h = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Length((area.width.saturating_sub(width)) / 2),
            Constraint::Length(width),
            Constraint::Min(0),
        ])
        .split(v[1]);
    h[1]
}

// ─────────────────── 添加路由 ───────────────────

pub fn draw_add_route(f: &mut Frame, app: &App) {
    let st = match &app.mode {
        Mode::AddRoute(st) => st,
        _ => return,
    };
    let area = f.area();
    let popup = centered_rect(60, 18, area);

    f.render_widget(Clear, popup);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),  // 输入框
            Constraint::Length(1),  // 提示
            Constraint::Min(3),    // 服务列表
            Constraint::Length(2), // 帮助
        ])
        .split(popup);

    let input_block = Block::default()
        .borders(Borders::ALL)
        .title(" IP 段 (CIDR，例如 10.0.0.0/8) ")
        .style(if st.focus == AddFocus::Input {
            Style::default().fg(Color::Yellow)
        } else {
            Style::default().fg(Color::DarkGray)
        });

    let input_text = format!("{}█", st.cidr_input); // 简单光标
    let input = Paragraph::new(input_text).block(input_block);
    f.render_widget(input, chunks[0]);

    let hint = Paragraph::new(Line::from(vec![
        Span::styled(" 目标网卡 ", Style::default().fg(Color::Gray)),
        Span::styled(
            "(Tab 切换焦点，↑↓ 选择，Enter 确认添加)",
            Style::default().fg(Color::DarkGray),
        ),
    ]));
    f.render_widget(hint, chunks[1]);

    // 服务列表
    let items: Vec<ListItem> = app
        .services
        .iter()
        .map(|s| {
            let marker = if s.enabled { "" } else { "[禁用] " };
            ListItem::new(Line::from(vec![
                Span::styled(
                    format!("  {:<6} ", s.device),
                    Style::default().fg(Color::Cyan),
                ),
                Span::raw(format!("{}({})", marker, s.name)),
            ]))
        })
        .collect();
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(" 网卡 / 服务 ")
                .style(if st.focus == AddFocus::ServiceList {
                    Style::default().fg(Color::Yellow)
                } else {
                    Style::default().fg(Color::DarkGray)
                }),
        )
        .highlight_style(
            Style::default()
                .bg(Color::DarkGray)
                .fg(Color::White)
                .add_modifier(Modifier::BOLD),
        )
        .highlight_symbol("▶ ");
    let mut list_state = ListState::default();
    list_state.select(Some(st.selected_service));
    f.render_stateful_widget(list, chunks[2], &mut list_state);

    let help = Paragraph::new(" [Esc] 取消    [Enter] 添加")
        .style(Style::default().fg(Color::DarkGray));
    f.render_widget(help, chunks[3]);
}

// ─────────────────── 删除确认 ───────────────────

pub fn draw_delete_confirm(
    f: &mut Frame,
    app: &App,
    binding_idx: usize,
    pos: usize,
) {
    let area = f.area();
    let popup = centered_rect(54, 10, area);
    f.render_widget(Clear, popup);

    let (route_str, dev_str, source_label) = match app.bindings.get(binding_idx) {
        Some(b) => {
            let entry = b.entries.get(pos);
            let dev = entry
                .and_then(|e| app.services.get(e.service_idx))
                .map(|s| format!("{} ({})", s.device, s.name))
                .unwrap_or_else(|| "<未知>".to_string());
            let source_label = entry
                .map(|e| e.source.label())
                .unwrap_or("?");
            (b.route.to_cidr(), dev, source_label)
        }
        None => ("<未知>".to_string(), "<未知>".to_string(), "?"),
    };

    let source_line = Line::from(vec![
        Span::styled("   来源: ", Style::default().fg(Color::Gray)),
        Span::styled(source_label.to_string(), Style::default().fg(Color::Yellow)),
    ]);

    let lines = vec![
        Line::from(vec![Span::styled(
            " 确认删除以下路由？",
            Style::default()
                .fg(Color::Yellow)
                .add_modifier(Modifier::BOLD),
        )]),
        Line::raw(""),
        Line::from(vec![
            Span::styled("   IP 段: ", Style::default().fg(Color::Gray)),
            Span::raw(route_str),
        ]),
        Line::from(vec![
            Span::styled("   网卡: ", Style::default().fg(Color::Gray)),
            Span::raw(dev_str),
        ]),
        source_line,
        Line::raw(""),
        Line::from(vec![
            Span::styled(" [Enter/y] ", Style::default().fg(Color::Green)),
            Span::raw("确认删除    "),
            Span::styled("[Esc/n] ", Style::default().fg(Color::Red)),
            Span::raw("取消"),
        ]),
        Line::raw(""),
        Line::from(Span::styled(
            " 提示：删除会触发 macOS 授权弹窗",
            Style::default().fg(Color::DarkGray),
        )),
    ];

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" 删除路由 ")
        .title_alignment(Alignment::Center)
        .style(Style::default().fg(Color::White));
    let p = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: false });
    f.render_widget(p, popup);
}

// ─────────────────── 帮助 ───────────────────

pub fn draw_help(f: &mut Frame) {
    let area = f.area();
    let popup = centered_rect(58, 16, area);
    f.render_widget(Clear, popup);

    let lines = vec![
        Line::from(Span::styled(
            " mac-route 帮助",
            Style::default()
                .fg(Color::Cyan)
                .add_modifier(Modifier::BOLD),
        )),
        Line::raw(""),
        Line::from(vec![
            Span::styled("  ↑/k       ", Style::default().fg(Color::Yellow)),
            Span::raw("上一个 IP 段"),
        ]),
        Line::from(vec![
            Span::styled("  ↓/j       ", Style::default().fg(Color::Yellow)),
            Span::raw("下一个 IP 段"),
        ]),
        Line::from(vec![
            Span::styled("  ←/h       ", Style::default().fg(Color::Yellow)),
            Span::raw("上一个绑定网卡"),
        ]),
        Line::from(vec![
            Span::styled("  →/l       ", Style::default().fg(Color::Yellow)),
            Span::raw("下一个绑定网卡"),
        ]),
        Line::from(vec![
            Span::styled("  r         ", Style::default().fg(Color::Yellow)),
            Span::raw("刷新（重新读取 networksetup）"),
        ]),
        Line::from(vec![
            Span::styled("  a         ", Style::default().fg(Color::Yellow)),
            Span::raw("添加路由（输入 CIDR + 选网卡）"),
        ]),
        Line::from(vec![
            Span::styled("  d         ", Style::default().fg(Color::Yellow)),
            Span::raw("删除当前选中的绑定"),
        ]),
        Line::from(vec![
            Span::styled("  ?         ", Style::default().fg(Color::Yellow)),
            Span::raw("显示此帮助"),
        ]),
        Line::from(vec![
            Span::styled("  q/Esc     ", Style::default().fg(Color::Yellow)),
            Span::raw("退出"),
        ]),
        Line::raw(""),
        Line::from(Span::styled(
            " 写操作（增删）会弹出 macOS 系统授权对话框，需要管理员密码。",
            Style::default().fg(Color::DarkGray),
        )),
        Line::from(Span::styled(
            " 按 Esc/Enter/q 关闭此帮助。",
            Style::default().fg(Color::DarkGray),
        )),
    ];

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" 帮助 ")
        .title_alignment(Alignment::Center);
    let p = Paragraph::new(lines).block(block).wrap(Wrap { trim: false });
    f.render_widget(p, popup);
}

// ─────────────────── 错误 ───────────────────

pub fn draw_error(f: &mut Frame, app: &App) {
    let area = f.area();
    let popup = centered_rect(64, 12, area);
    f.render_widget(Clear, popup);

    let msg = app
        .last_error
        .clone()
        .unwrap_or_else(|| "未知错误".to_string());

    let lines = vec![
        Line::from(Span::styled(
            " 发生错误",
            Style::default()
                .fg(Color::Red)
                .add_modifier(Modifier::BOLD),
        )),
        Line::raw(""),
        Line::raw(msg.clone()),
        Line::raw(""),
        Line::raw(""),
        Line::from(Span::styled(
            " 按 Esc/Enter/空格 关闭",
            Style::default().fg(Color::DarkGray),
        )),
    ];

    let block = Block::default()
        .borders(Borders::ALL)
        .title(" 错误 ")
        .title_alignment(Alignment::Center)
        .style(Style::default().fg(Color::Red));
    let p = Paragraph::new(lines)
        .block(block)
        .wrap(Wrap { trim: true });
    f.render_widget(p, popup);
}
