use crate::app::AppState;
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Gauge, Paragraph};

// Color constants matching the TUI palette (exact match from layout.rs)
const BRAND_PURPLE: Color = Color::Rgb(138, 43, 226);
#[allow(dead_code)]
const BRAND_VIOLET: Color = Color::Rgb(148, 103, 189);
const CYBER_CYAN: Color = Color::Rgb(0, 255, 255);
const NEON_GREEN: Color = Color::Rgb(57, 255, 20);
const TEXT_PRIMARY: Color = Color::Rgb(230, 230, 240);
const TEXT_DIM: Color = Color::Rgb(100, 100, 120);
#[allow(dead_code)]
const TEXT_MUTED: Color = Color::Rgb(60, 60, 80);
const BG_PANEL: Color = Color::Rgb(18, 18, 25);

/// Exact logo from requirements (monospace, preserve spacing)
const LOGO: &str = r#"██╗  ██╗██████╗ ██╗   ██╗███╗   ██╗██████╗      ██████╗ ███████╗
██║  ██║██╔══██╗██║   ██║████╗  ██║██╔══██╗    ██╔═══██╗██╔════╝
███████║██████╔╝██║   ██║██╔██╗ ██║██████╔╝    ██║   ██║███████╗
╚════██║██╔══██╗██║   ██║██║╚██╗██║██╔══██╗    ██║   ██║╚════██║
     ██║██║  ██║╚██████╔╝██║ ╚████║██║  ██║    ╚██████╔╝███████║
     ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚═╝  ╚═══╝╚═╝  ╚═╝     ╚═════╝ ╚══════╝"#;

pub fn render_boot(f: &mut Frame, area: Rect, state: &AppState) {
    // Clear background
    f.render_widget(Block::default().style(Style::default().bg(BG_PANEL)), area);

    // Fixed layout: logo stays at fixed position, elements below it
    let logo_height: u16 = 6; // Logo is 6 lines
    let boot_logs_height: u16 = 5; // Fixed height for logs (not dynamic)
    let progress_height: u16 = 3;

    // Logo starts at a fixed position from top (about 1/4 down the screen)
    let logo_start_y: u16 = area.height / 4;

    // === LOGO (centered horizontally, fixed vertical position) ===
    let logo_lines: Vec<&str> = LOGO.lines().collect();
    let logo_width: u16 = logo_lines.iter().map(|l| l.len()).max().unwrap_or(0) as u16;
    // Center horizontally: (area.width - logo_width) / 2
    let logo_x: u16 = area.x + (area.width.saturating_sub(logo_width)) / 2;

    for (i, line) in logo_lines.iter().enumerate() {
        let line_y = logo_start_y + i as u16;
        if line_y < area.height {
            // Center each line within the available width
            let line_rect = Rect {
                x: logo_x,
                y: line_y,
                width: logo_width.min(area.width.saturating_sub(logo_x)),
                height: 1,
            };
            f.render_widget(
                Paragraph::new(*line)
                    .style(Style::default().fg(BRAND_PURPLE))
                    .alignment(Alignment::Center), // Center alignment for perfect centering
                line_rect,
            );
        }
    }

    let current_y = logo_start_y + logo_height + 2;

    // === BOOT LOGS ===
    if !state.boot_lines.is_empty() && current_y < area.height {
        // Center logs horizontally
        let logs_width: u16 = (area.width * 60 / 100).min(area.width.saturating_sub(40)); // 60% width, safe margins
        let logs_x: u16 = area.x + (area.width.saturating_sub(logs_width)) / 2;

        let logs_area = Rect {
            x: logs_x,
            y: current_y,
            width: logs_width,
            height: boot_logs_height,
        };

        let mut log_text = String::new();
        for line in state.boot_lines.iter() {
            log_text.push_str(line);
            log_text.push('\n');
        }

        f.render_widget(
            Paragraph::new(log_text.trim())
                .style(Style::default().fg(TEXT_PRIMARY))
                .alignment(Alignment::Center), // Center logs too
            logs_area,
        );
    }

    let current_y = current_y + boot_logs_height + 2;

    // === PROGRESS BAR ===
    if current_y < area.height {
        // Center progress bar horizontally
        let progress_width: u16 = (area.width * 60 / 100).min(area.width.saturating_sub(40));
        let progress_x: u16 = area.x + (area.width.saturating_sub(progress_width)) / 2;

        let progress_area = Rect {
            x: progress_x,
            y: current_y,
            width: progress_width,
            height: 3,
        };

        let progress_label = if state.boot_done {
            "System Ready"
        } else {
            "Booting..."
        };

        f.render_widget(
            Gauge::default()
                .block(
                    Block::default()
                        .borders(Borders::NONE)
                        .title(progress_label)
                        .title_style(Style::default().fg(CYBER_CYAN)),
                )
                .gauge_style(Style::default().fg(NEON_GREEN))
                .percent(state.boot_progress as u16)
                .label(format!("{}%", state.boot_progress)),
            progress_area,
        );
    }

    let current_y = current_y + progress_height + 2;

    // === FOOTER: "Press any key to continue" (only when boot done) ===
    if state.boot_done && current_y < area.height {
        let footer_area = Rect {
            x: area.x,
            y: current_y,
            width: area.width,
            height: 1,
        };

        f.render_widget(
            Paragraph::new("Press any key to continue...")
                .style(Style::default().fg(TEXT_DIM))
                .alignment(Alignment::Center),
            footer_area,
        );
    }
}
