// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
use anyhow::Result;
use crossterm::{
    event::{self, Event, KeyCode},
    execute,
    terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
};
use ratatui::{
    prelude::*,
    widgets::{Block, Borders, Paragraph, Gauge},
};
use std::{io, time::Duration};

pub async fn run_radar_dashboard() -> Result<()> {
    enable_raw_mode()?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)?;
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut intercept_rate: u16 = 0;

    loop {
        terminal.draw(|f| {
            let size = f.size();
            let chunks = Layout::default()
                .direction(Direction::Vertical)
                .margin(2)
                .constraints([Constraint::Length(3), Constraint::Min(2), Constraint::Length(3)].as_ref())
                .split(size);

            let header = Paragraph::new("XCU QUANTUM RADAR (eBPF & X-Grid Monitor)")
                .style(Style::default().fg(Color::Green).add_modifier(Modifier::BOLD))
                .block(Block::default().borders(Borders::ALL).title("STATUS: ONLINE"));
            f.render_widget(header, chunks[0]);

            let matrix_view = Paragraph::new("X-Grid Nodes: [xc.ultramodul.xyz] [sg1.ultramodul.xyz]\nZero-Copy Memory: Active\nGlommio Cores: 16/16 Pinned\nAV1 Spatial Router: 1042 ABR Drops/sec")
                .style(Style::default().fg(Color::Cyan))
                .block(Block::default().borders(Borders::ALL).title("INTELLIGENCE"));
            f.render_widget(matrix_view, chunks[1]);

            let gauge = Gauge::default()
                .block(Block::default().title("eBPF Intercept Rate (Packets/sec)").borders(Borders::ALL))
                .gauge_style(Style::default().fg(Color::Red))
                .percent(intercept_rate % 100);
            f.render_widget(gauge, chunks[2]);
        })?;

        intercept_rate = intercept_rate.wrapping_add(5);

        if event::poll(Duration::from_millis(100))? {
            if let Event::Key(key) = event::read()? {
                if key.code == KeyCode::Char('q') {
                    break;
                }
            }
        }
    }

    disable_raw_mode()?;
    execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
    terminal.show_cursor()?;
    Ok(())
}
