use crate::app::{AgentInfo, AppState};
/// Agent List Screen
/// View and manage AI agents
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Cell, Paragraph, Row, Table, Wrap};

// === 4RUNR BRAND COLORS ===
const BRAND_PURPLE: Color = Color::Rgb(138, 43, 226);
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);
const TEXT_MUTED: Color = Color::Rgb(60, 60, 80);
const BG_PANEL: Color = Color::Rgb(18, 18, 25);

/// Render agent list screen
pub fn render(f: &mut Frame, state: &AppState) {
    let area = f.size();

    if state.agent_list.detail_view.is_some() {
        // Render detail popup
        render_detail_popup(f, area, state);
    } else {
        // Render list view
        render_list_view(f, area, state);
    }
}

fn render_list_view(f: &mut Frame, area: Rect, state: &AppState) {
    use ratatui::layout::{Constraint, Direction, Layout};

    // Split into header, content, footer
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // Header
            Constraint::Min(0),    // Content
            Constraint::Length(3), // Footer
        ])
        .split(area);

    // === HEADER ===
    let agent_count = state.agent_list.agents.len();
    let header_block = Block::default()
        .title(format!(" 🤖 Agent List ({} agents) ", agent_count))
        .title_style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    f.render_widget(header_block, chunks[0]);

    // === CONTENT: Agent Table ===
    let content_block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(TEXT_MUTED))
        .style(Style::default().bg(BG_PANEL));

    let table_area = content_block.inner(chunks[1]);
    f.render_widget(content_block, chunks[1]);

    if state.agent_list.agents.is_empty() {
        // Show "No agents" message
        f.render_widget(
            Paragraph::new("No agents available.\n\nUse Agent Builder to create new agents.")
                .style(Style::default().fg(TEXT_DIM))
                .alignment(Alignment::Center),
            table_area,
        );
    } else {
        // Create table rows
        let rows: Vec<Row> = state
            .agent_list
            .agents
            .iter()
            .enumerate()
            .map(|(i, agent)| {
                let is_selected = i == state.agent_list.selected_index;
                let style = if is_selected {
                    Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD)
                } else {
                    Style::default().fg(TEXT_PRIMARY)
                };

                let name = if is_selected {
                    format!("▶ {}", agent.name)
                } else {
                    format!("  {}", agent.name)
                };

                let desc = agent
                    .description
                    .as_deref()
                    .unwrap_or("No description")
                    .chars()
                    .take(30)
                    .collect::<String>();
                let model = agent.model.chars().take(15).collect::<String>();
                let provider = agent.provider.chars().take(10).collect::<String>();

                Row::new(vec![
                    Cell::from(name).style(style),
                    Cell::from(desc).style(style),
                    Cell::from(model).style(style),
                    Cell::from(provider).style(style),
                ])
            })
            .collect();

        let table = Table::new(
            rows,
            [
                Constraint::Percentage(25),
                Constraint::Percentage(35),
                Constraint::Percentage(20),
                Constraint::Percentage(20),
            ],
        )
        .header(Row::new(vec![
            Cell::from("Name").style(Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD)),
            Cell::from("Description")
                .style(Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD)),
            Cell::from("Model").style(Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD)),
            Cell::from("Provider")
                .style(Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD)),
        ]))
        .column_spacing(1)
        .style(Style::default().fg(TEXT_PRIMARY));

        f.render_widget(table, table_area);
    }

    // === FOOTER ===
    let footer_text = Line::from(vec![
        Span::styled("↑/↓", Style::default().fg(CYBER_CYAN)),
        Span::styled(" Navigate  |  ", Style::default().fg(TEXT_DIM)),
        Span::styled("Enter", Style::default().fg(NEON_GREEN)),
        Span::styled(" View Details  |  ", Style::default().fg(TEXT_DIM)),
        Span::styled("D/Del", Style::default().fg(Color::Rgb(255, 100, 100))),
        Span::styled(" Delete  |  ", Style::default().fg(TEXT_DIM)),
        Span::styled("ESC", Style::default().fg(BRAND_PURPLE)),
        Span::styled(" Close", Style::default().fg(TEXT_DIM)),
    ]);

    f.render_widget(
        Paragraph::new(footer_text)
            .alignment(Alignment::Center)
            .style(Style::default().bg(BG_PANEL))
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(TEXT_MUTED)),
            ),
        chunks[2],
    );
}

fn render_detail_popup(f: &mut Frame, area: Rect, state: &AppState) {
    // First render a full-screen dim overlay
    let dim_overlay = Block::default().style(Style::default().bg(Color::Black));
    f.render_widget(dim_overlay, area);

    // Then render detail popup on top
    let detail_index = state.agent_list.detail_view.unwrap();
    if let Some(agent) = state.agent_list.agents.get(detail_index) {
        render_agent_detail(f, area, agent);
    }
}

fn render_agent_detail(f: &mut Frame, area: Rect, agent: &AgentInfo) {
    use ratatui::layout::{Constraint, Direction, Layout};

    // Calculate popup size (75% width, 85% height, centered)
    let popup_width = (area.width * 75 / 100).max(60);
    let popup_height = (area.height * 85 / 100).max(20);
    let popup_x = (area.width.saturating_sub(popup_width)) / 2;
    let popup_y = (area.height.saturating_sub(popup_height)) / 2;

    let popup_area = Rect {
        x: popup_x,
        y: popup_y,
        width: popup_width,
        height: popup_height,
    };

    // Render detail popup block
    let detail_block = Block::default()
        .title(format!(" 📋 Agent Details: {} ", agent.name))
        .title_style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        )
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    let inner = detail_block.inner(popup_area);
    f.render_widget(detail_block, popup_area);

    // Split inner area for better layout
    let content_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),    // Main content
            Constraint::Length(2), // Footer
        ])
        .split(inner);

    // Create detail text with better spacing
    let mut detail_lines = vec![
        Line::from(""), // Top padding
        Line::from(vec![
            Span::styled(
                "Name:              ",
                Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
            ),
            Span::styled(&agent.name, Style::default().fg(NEON_GREEN)),
        ]),
        Line::from(""),
    ];

    if let Some(desc) = &agent.description {
        detail_lines.push(Line::from(vec![
            Span::styled(
                "Description:       ",
                Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
            ),
            Span::styled(desc, Style::default().fg(TEXT_PRIMARY)),
        ]));
        detail_lines.push(Line::from(""));
    }

    detail_lines.push(Line::from(vec![
        Span::styled(
            "Model:             ",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        ),
        Span::styled(&agent.model, Style::default().fg(TEXT_PRIMARY)),
    ]));
    detail_lines.push(Line::from(""));

    detail_lines.push(Line::from(vec![
        Span::styled(
            "Provider:          ",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        ),
        Span::styled(&agent.provider, Style::default().fg(TEXT_PRIMARY)),
    ]));
    detail_lines.push(Line::from(""));

    if let Some(temp) = agent.temperature {
        detail_lines.push(Line::from(vec![
            Span::styled(
                "Temperature:       ",
                Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("{:.2}", temp), Style::default().fg(TEXT_PRIMARY)),
        ]));
        detail_lines.push(Line::from(""));
    }

    if let Some(max_tokens) = agent.max_tokens {
        detail_lines.push(Line::from(vec![
            Span::styled(
                "Max Tokens:        ",
                Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
            ),
            Span::styled(format!("{}", max_tokens), Style::default().fg(TEXT_PRIMARY)),
        ]));
        detail_lines.push(Line::from(""));
    }

    if !agent.tools.is_empty() {
        detail_lines.push(Line::from(""));
        detail_lines.push(Line::from(vec![Span::styled(
            "Tools:",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        )]));
        for tool in &agent.tools {
            detail_lines.push(Line::from(vec![
                Span::raw("  • "),
                Span::styled(tool, Style::default().fg(NEON_GREEN)),
            ]));
        }
        detail_lines.push(Line::from(""));
    }

    if let Some(prompt) = &agent.system_prompt {
        detail_lines.push(Line::from(""));
        detail_lines.push(Line::from(vec![Span::styled(
            "System Prompt:",
            Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD),
        )]));
        detail_lines.push(Line::from(""));
        // Show first 300 chars of prompt
        let prompt_preview = prompt.chars().take(300).collect::<String>();
        // Simple word wrapping
        let wrap_width = (popup_width.saturating_sub(6)) as usize;
        let words: Vec<&str> = prompt_preview.split_whitespace().collect();
        let mut current_line = String::from("  ");

        for word in words {
            if current_line.len() + word.len() + 1 > wrap_width {
                detail_lines
                    .push(Line::from(current_line.clone()).style(Style::default().fg(TEXT_DIM)));
                current_line = format!("  {}", word);
            } else {
                if current_line.len() > 2 {
                    current_line.push(' ');
                }
                current_line.push_str(word);
            }
        }
        if current_line.len() > 2 {
            detail_lines.push(Line::from(current_line).style(Style::default().fg(TEXT_DIM)));
        }
    }

    // Render main content
    f.render_widget(
        Paragraph::new(detail_lines).wrap(Wrap { trim: false }),
        content_chunks[0],
    );

    // Render footer
    let footer_text = Line::from(vec![
        Span::styled("Press ", Style::default().fg(TEXT_DIM)),
        Span::styled(
            "ESC",
            Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
        ),
        Span::styled(" to close", Style::default().fg(TEXT_DIM)),
    ]);

    f.render_widget(
        Paragraph::new(footer_text).alignment(Alignment::Center),
        content_chunks[1],
    );
}
