use crate::app::AppState;
/// Agent Builder Screen
/// Multi-step wizard for creating and editing agents
use ratatui::prelude::*;
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};

// === 4RUNR BRAND COLORS (matching 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 AMBER_WARN: Color = Color::Rgb(255, 191, 0);
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);

// === MODEL INFORMATION ===
struct ModelInfo {
    context_window: u32,
    max_output: u32,
    training_cutoff: &'static str,
    capabilities: Vec<&'static str>,
}

fn get_model_info(provider: &str, model: &str) -> ModelInfo {
    match (provider, model) {
        // OpenAI
        ("openai", "gpt-4") => ModelInfo {
            context_window: 8192,
            max_output: 4096,
            training_cutoff: "Sep 2021",
            capabilities: vec!["Text", "Code", "Analysis"],
        },
        ("openai", "gpt-4-turbo") => ModelInfo {
            context_window: 128000,
            max_output: 4096,
            training_cutoff: "Apr 2023",
            capabilities: vec!["Text", "Code", "Vision", "JSON"],
        },
        ("openai", "gpt-3.5-turbo") => ModelInfo {
            context_window: 16385,
            max_output: 4096,
            training_cutoff: "Sep 2021",
            capabilities: vec!["Text", "Code"],
        },

        // Anthropic
        ("anthropic", "claude-3-opus") => ModelInfo {
            context_window: 200000,
            max_output: 4096,
            training_cutoff: "Aug 2023",
            capabilities: vec!["Text", "Code", "Vision", "Analysis", "Long Context"],
        },
        ("anthropic", "claude-3-sonnet") => ModelInfo {
            context_window: 200000,
            max_output: 4096,
            training_cutoff: "Aug 2023",
            capabilities: vec!["Text", "Code", "Vision", "Balanced"],
        },
        ("anthropic", "claude-3-haiku") => ModelInfo {
            context_window: 200000,
            max_output: 4096,
            training_cutoff: "Aug 2023",
            capabilities: vec!["Text", "Code", "Fast", "Efficient"],
        },

        // Local models
        _ => ModelInfo {
            context_window: 4096,
            max_output: 2048,
            training_cutoff: "Varies",
            capabilities: vec!["Text", "Local", "Private"],
        },
    }
}

// === COST CALCULATOR ===
/// Pricing data for different AI providers (per 1M tokens)
struct ModelPricing {
    input_cost: f64,  // USD per 1M input tokens
    output_cost: f64, // USD per 1M output tokens
}

fn get_model_pricing(provider: &str, model: &str) -> ModelPricing {
    match (provider, model) {
        // OpenAI
        ("openai", "gpt-4") => ModelPricing {
            input_cost: 30.0,
            output_cost: 60.0,
        },
        ("openai", "gpt-4-turbo") => ModelPricing {
            input_cost: 10.0,
            output_cost: 30.0,
        },
        ("openai", "gpt-3.5-turbo") => ModelPricing {
            input_cost: 0.5,
            output_cost: 1.5,
        },

        // Anthropic
        ("anthropic", "claude-3-opus") => ModelPricing {
            input_cost: 15.0,
            output_cost: 75.0,
        },
        ("anthropic", "claude-3-sonnet") => ModelPricing {
            input_cost: 3.0,
            output_cost: 15.0,
        },
        ("anthropic", "claude-3-haiku") => ModelPricing {
            input_cost: 0.25,
            output_cost: 1.25,
        },

        // Local models (free)
        _ => ModelPricing {
            input_cost: 0.0,
            output_cost: 0.0,
        },
    }
}

struct CostEstimate {
    cost_1k: f64,
    cost_10k: f64,
    cost_100k: f64,
    cost_1m: f64,
    is_free: bool,
}

fn calculate_cost(provider: &str, model: &str, _max_tokens: u32) -> CostEstimate {
    let pricing = get_model_pricing(provider, model);
    let is_free = pricing.input_cost == 0.0 && pricing.output_cost == 0.0;

    if is_free {
        return CostEstimate {
            cost_1k: 0.0,
            cost_10k: 0.0,
            cost_100k: 0.0,
            cost_1m: 0.0,
            is_free: true,
        };
    }

    // Assume 50/50 split between input and output tokens for estimation
    let avg_cost_per_1m = (pricing.input_cost + pricing.output_cost) / 2.0;

    CostEstimate {
        cost_1k: avg_cost_per_1m / 1000.0,
        cost_10k: avg_cost_per_1m / 100.0,
        cost_100k: avg_cost_per_1m / 10.0,
        cost_1m: avg_cost_per_1m,
        is_free: false,
    }
}

/// Agent Builder wizard state
#[derive(Debug, Clone)]
pub struct AgentBuilderState {
    pub current_step: usize, // 1-6
    pub focused_field: usize,

    // Step 1: Basic Info
    pub name: String,
    pub description: String,

    // Step 2: Model Selection
    pub use_local_model: bool,
    pub provider: String,       // "openai", "anthropic", "ollama", etc.
    pub model: String,          // "gpt-4", "claude-3", "llama2", etc.
    pub local_provider: String, // "ollama", "lm-studio", "custom"
    pub local_model: String,
    pub local_url: String,

    // Step 3: System Prompt
    pub system_prompt: String,

    // Step 4: Parameters
    pub temperature: f32,
    pub max_tokens: u32,
    pub top_p: f32,
    pub frequency_penalty: f32,
    pub presence_penalty: f32,

    // Step 5: Tools
    pub selected_tools: Vec<String>,
    pub available_tools: Vec<String>,

    // Validation
    pub validation_errors: Vec<String>,
}

impl Default for AgentBuilderState {
    fn default() -> Self {
        Self {
            current_step: 1,
            focused_field: 0,
            name: String::new(),
            description: String::new(),
            use_local_model: false,
            provider: "openai".to_string(),
            model: "gpt-4".to_string(),
            local_provider: "ollama".to_string(),
            local_model: "llama2".to_string(),
            local_url: "http://localhost:11434".to_string(),
            system_prompt: String::new(),
            temperature: 0.7,
            max_tokens: 2000,
            top_p: 1.0,
            frequency_penalty: 0.0,
            presence_penalty: 0.0,
            selected_tools: Vec::new(),
            available_tools: vec![
                "calculator".to_string(),
                "time".to_string(),
                "weather".to_string(),
            ],
            validation_errors: Vec::new(),
        }
    }
}

impl AgentBuilderState {
    /// Validate current step
    pub fn validate_step(&mut self) -> bool {
        self.validation_errors.clear();

        match self.current_step {
            1 => {
                if self.name.trim().is_empty() {
                    self.validation_errors.push("Name is required".to_string());
                }
                if self.name.len() > 50 {
                    self.validation_errors
                        .push("Name must be 50 characters or less".to_string());
                }
            }
            2 => {
                if !self.use_local_model && self.model.is_empty() {
                    self.validation_errors.push("Model is required".to_string());
                }
                if self.use_local_model && self.local_model.is_empty() {
                    self.validation_errors
                        .push("Local model is required".to_string());
                }
            }
            3 => {
                // System prompt is optional
            }
            4 => {
                if !(0.0..=2.0).contains(&self.temperature) {
                    self.validation_errors
                        .push("Temperature must be between 0.0 and 2.0".to_string());
                }
                if self.max_tokens < 1 || self.max_tokens > 100000 {
                    self.validation_errors
                        .push("Max tokens must be between 1 and 100000".to_string());
                }
            }
            5 => {
                // Tools are optional
            }
            6 => {
                // Review step - validate all
                if self.name.trim().is_empty() {
                    self.validation_errors.push("Name is required".to_string());
                }
            }
            _ => {}
        }

        self.validation_errors.is_empty()
    }

    /// Move to next step
    pub fn next_step(&mut self) -> bool {
        if self.validate_step() && self.current_step < 6 {
            self.current_step += 1;
            self.focused_field = 0;
            true
        } else {
            false
        }
    }

    /// Move to previous step
    pub fn prev_step(&mut self) {
        if self.current_step > 1 {
            self.current_step -= 1;
            self.focused_field = 0;
        }
    }

    /// Move to next field within current step
    pub fn next_field(&mut self) {
        let max_field = self.get_max_field_for_step();
        if self.focused_field < max_field {
            self.focused_field += 1;
        }
    }

    /// Move to previous field within current step
    pub fn prev_field(&mut self) {
        if self.focused_field > 0 {
            self.focused_field -= 1;
        }
    }

    /// Get the maximum field index for the current step
    fn get_max_field_for_step(&self) -> usize {
        match self.current_step {
            1 => 1,                                            // Name, Description
            2 => 4, // Provider, Model, Local Provider, Local Model, Local URL
            3 => 0, // System Prompt (single field)
            4 => 4, // Temperature, Max Tokens, Top P, Frequency Penalty, Presence Penalty
            5 => self.available_tools.len().saturating_sub(1), // Tools list
            6 => 0, // Review (no editable fields)
            _ => 0,
        }
    }
}

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

    // Get wizard state from AppState
    let wizard_state = &state.agent_builder;

    render_wizard(f, area, wizard_state);
}

fn render_wizard(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    use ratatui::layout::{Constraint, Direction, Layout};

    // Split area into content and footer
    let v_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(10),   // Content
            Constraint::Length(3), // Navigation footer
        ])
        .split(area);

    // Split content into main wizard and cost calculator (if on step 2 or 4)
    let show_cost_calc = wizard.current_step == 2 || wizard.current_step == 4;
    let h_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints(if show_cost_calc {
            [
                Constraint::Percentage(65), // Wizard content
                Constraint::Percentage(35), // Cost calculator
            ]
            .as_ref()
        } else {
            [
                Constraint::Percentage(100), // Full width
                Constraint::Length(0),       // No cost calc
            ]
            .as_ref()
        })
        .split(v_chunks[0]);

    // Progress bar for title
    let progress = wizard.current_step as f32 / 6.0;
    let filled = (progress * 20.0) as usize;
    let empty = 20 - filled;
    let progress_bar = format!("[{}{}]", "█".repeat(filled), "░".repeat(empty));

    // Main container with brand styling
    let block = Block::default()
        .title(format!(
            " 🤖 Agent Builder - Step {}/6 {} ",
            wizard.current_step, progress_bar
        ))
        .title_style(Style::default().fg(CYBER_CYAN).add_modifier(Modifier::BOLD))
        .borders(Borders::ALL)
        .border_style(Style::default().fg(BRAND_PURPLE))
        .style(Style::default().bg(BG_PANEL));

    let inner = block.inner(h_chunks[0]);
    f.render_widget(block, h_chunks[0]);

    // Render current step
    match wizard.current_step {
        1 => render_step_1_basic_info(f, inner, wizard),
        2 => render_step_2_model_selection(f, inner, wizard),
        3 => render_step_3_system_prompt(f, inner, wizard),
        4 => render_step_4_parameters(f, inner, wizard),
        5 => render_step_5_tools(f, inner, wizard),
        6 => render_step_6_review(f, inner, wizard),
        _ => {}
    }

    // Render cost calculator if visible
    if show_cost_calc {
        render_cost_calculator(f, h_chunks[1], wizard);
    }

    // Render navigation footer
    render_navigation_footer(f, v_chunks[1], wizard);
}

fn render_cost_calculator(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    use ratatui::layout::{Constraint, Direction, Layout};

    // Split into cost and model info sections
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Percentage(60), // Cost info
            Constraint::Percentage(40), // Model info
        ])
        .split(area);

    let provider = if wizard.use_local_model {
        "local"
    } else {
        &wizard.provider
    };
    let model = if wizard.use_local_model {
        &wizard.local_model
    } else {
        &wizard.model
    };

    let cost = calculate_cost(provider, model, wizard.max_tokens);
    let model_info = get_model_info(provider, model);

    // === COST SECTION ===
    let cost_block = Block::default()
        .title(" 💰 Cost Estimator ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(AMBER_WARN))
        .style(Style::default().bg(BG_PANEL));

    let cost_inner = cost_block.inner(chunks[0]);
    f.render_widget(cost_block, chunks[0]);

    let text = if cost.is_free {
        vec![
            Line::from(""),
            Line::from(vec![
                Span::styled("✓ ", Style::default().fg(NEON_GREEN)),
                Span::styled("Local Model", Style::default().fg(NEON_GREEN).bold()),
            ]),
            Line::from(""),
            Line::from(vec![Span::styled(
                "FREE",
                Style::default()
                    .fg(NEON_GREEN)
                    .bold()
                    .add_modifier(Modifier::UNDERLINED),
            )]),
            Line::from(""),
            Line::from("No API costs!").style(Style::default().fg(TEXT_DIM)),
            Line::from("Self-hosted model").style(Style::default().fg(TEXT_DIM)),
            Line::from(""),
            Line::from("Benefits:").style(Style::default().fg(TEXT_PRIMARY).bold()),
            Line::from("  • No usage limits").style(Style::default().fg(TEXT_DIM)),
            Line::from("  • Full privacy").style(Style::default().fg(TEXT_DIM)),
            Line::from("  • No API keys").style(Style::default().fg(TEXT_DIM)),
        ]
    } else {
        let cost_color = if cost.cost_1k < 0.01 {
            NEON_GREEN
        } else if cost.cost_1k < 0.05 {
            AMBER_WARN
        } else {
            Color::Rgb(255, 69, 69)
        };

        vec![
            Line::from(""),
            Line::from(vec![
                Span::styled("Provider: ", Style::default().fg(TEXT_DIM)),
                Span::styled(provider, Style::default().fg(TEXT_PRIMARY).bold()),
            ]),
            Line::from(vec![
                Span::styled("Model: ", Style::default().fg(TEXT_DIM)),
                Span::styled(model, Style::default().fg(TEXT_PRIMARY)),
            ]),
            Line::from(""),
            Line::from("Estimated Cost:").style(Style::default().fg(TEXT_PRIMARY).bold()),
            Line::from(""),
            Line::from(vec![
                Span::styled("  1K tokens:   ", Style::default().fg(TEXT_DIM)),
                Span::styled(
                    format!("${:.4}", cost.cost_1k),
                    Style::default().fg(cost_color),
                ),
            ]),
            Line::from(vec![
                Span::styled("  10K tokens:  ", Style::default().fg(TEXT_DIM)),
                Span::styled(
                    format!("${:.3}", cost.cost_10k),
                    Style::default().fg(cost_color),
                ),
            ]),
            Line::from(vec![
                Span::styled("  100K tokens: ", Style::default().fg(TEXT_DIM)),
                Span::styled(
                    format!("${:.2}", cost.cost_100k),
                    Style::default().fg(cost_color),
                ),
            ]),
            Line::from(vec![
                Span::styled("  1M tokens:   ", Style::default().fg(TEXT_DIM)),
                Span::styled(
                    format!("${:.2}", cost.cost_1m),
                    Style::default().fg(cost_color),
                ),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::styled("Max tokens: ", Style::default().fg(TEXT_DIM)),
                Span::styled(
                    format!("{}", wizard.max_tokens),
                    Style::default().fg(CYBER_CYAN),
                ),
            ]),
        ]
    };

    let cost_paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(cost_paragraph, cost_inner);

    // === MODEL INFO SECTION ===
    let info_block = Block::default()
        .title(" 📊 Model Info ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(CYBER_CYAN))
        .style(Style::default().bg(BG_PANEL));

    let info_inner = info_block.inner(chunks[1]);
    f.render_widget(info_block, chunks[1]);

    let info_text = vec![
        Line::from(""),
        Line::from(vec![
            Span::styled("Context: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("{} tokens", model_info.context_window),
                Style::default().fg(NEON_GREEN),
            ),
        ]),
        Line::from(vec![
            Span::styled("Max Output: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("{} tokens", model_info.max_output),
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
        Line::from(vec![
            Span::styled("Training: ", Style::default().fg(TEXT_DIM)),
            Span::styled(model_info.training_cutoff, Style::default().fg(TEXT_MUTED)),
        ]),
        Line::from(""),
        Line::from("Capabilities:").style(Style::default().fg(TEXT_PRIMARY).bold()),
        Line::from(
            model_info
                .capabilities
                .iter()
                .map(|cap| format!("  • {}", cap))
                .collect::<Vec<_>>()
                .join("\n"),
        )
        .style(Style::default().fg(TEXT_DIM)),
    ];

    let info_paragraph = Paragraph::new(info_text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(info_paragraph, info_inner);
}

fn render_navigation_footer(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let block = Block::default()
        .title(" ⌨️  Navigation ")
        .borders(Borders::ALL)
        .border_style(Style::default().fg(TEXT_DIM))
        .style(Style::default().bg(BG_PANEL));

    let inner = block.inner(area);
    f.render_widget(block, area);

    let can_go_back = wizard.current_step > 1;
    let is_final_step = wizard.current_step == 6;

    let nav_text = if is_final_step {
        Line::from(vec![
            Span::styled(
                "←",
                Style::default()
                    .fg(if can_go_back { CYBER_CYAN } else { TEXT_MUTED })
                    .bold(),
            ),
            Span::styled(" Back  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Tab/↑↓", Style::default().fg(CYBER_CYAN).bold()),
            Span::styled(" Navigate  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Enter", Style::default().fg(NEON_GREEN).bold()),
            Span::styled(" Create Agent  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("ESC", Style::default().fg(Color::Rgb(255, 69, 69)).bold()),
            Span::styled(" Cancel", Style::default().fg(TEXT_DIM)),
        ])
    } else {
        Line::from(vec![
            Span::styled(
                "←",
                Style::default()
                    .fg(if can_go_back { CYBER_CYAN } else { TEXT_MUTED })
                    .bold(),
            ),
            Span::styled(" Back  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("Tab/↑↓", Style::default().fg(CYBER_CYAN).bold()),
            Span::styled(" Navigate  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("→/Enter", Style::default().fg(NEON_GREEN).bold()),
            Span::styled(" Next  │  ", Style::default().fg(TEXT_DIM)),
            Span::styled("ESC", Style::default().fg(Color::Rgb(255, 69, 69)).bold()),
            Span::styled(" Cancel", Style::default().fg(TEXT_DIM)),
        ])
    };

    let paragraph = Paragraph::new(nav_text)
        .style(Style::default().fg(TEXT_PRIMARY))
        .alignment(Alignment::Center);

    f.render_widget(paragraph, inner);
}

fn render_step_1_basic_info(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let focused = wizard.focused_field;

    let text = vec![
        Line::from(""),
        Line::from("Step 1: Basic Information").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                if focused == 0 { "▶ " } else { "  " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Name: "),
            Span::styled(&wizard.name, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 0 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from("    (Required, max 50 characters)").style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                if focused == 1 { "▶ " } else { "  " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Description: "),
            Span::styled(&wizard.description, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 1 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from("    (Optional, brief description of agent purpose)")
            .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from(""),
        Line::from("Navigation:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  Tab/Shift+Tab/↑↓ - Move between fields").style(Style::default().fg(TEXT_DIM)),
        Line::from("  Enter - Next step").style(Style::default().fg(TEXT_DIM)),
        Line::from("  ESC - Cancel and return to Main").style(Style::default().fg(TEXT_DIM)),
    ];

    // Show validation errors if any
    let mut all_lines = text;
    if !wizard.validation_errors.is_empty() {
        all_lines.push(Line::from(""));
        all_lines.push(
            Line::from("Validation Errors:")
                .style(Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)),
        );
        for error in &wizard.validation_errors {
            all_lines
                .push(Line::from(format!("  • {}", error)).style(Style::default().fg(Color::Red)));
        }
    }

    let paragraph = Paragraph::new(all_lines)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}

fn render_step_2_model_selection(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let focused = wizard.focused_field;
    let model_type = if wizard.use_local_model {
        "Local"
    } else {
        "Remote"
    };

    let text = vec![
        Line::from(""),
        Line::from("Step 2: Model Selection").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from(vec![
            Span::raw("Model Type: "),
            Span::styled(model_type, Style::default().fg(CYBER_CYAN)),
        ]),
        Line::from("  [ ] Remote (OpenAI, Anthropic, etc.)").style(Style::default().fg(TEXT_DIM)),
        Line::from("  [ ] Local (Ollama, LM Studio, etc.)").style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from("Remote Model:").style(
            Style::default()
                .fg(TEXT_PRIMARY)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(vec![
            Span::styled(
                if focused == 0 { "  ▶ " } else { "    " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Provider: "),
            Span::styled(&wizard.provider, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 0 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                if focused == 1 { "  ▶ " } else { "    " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Model: "),
            Span::styled(&wizard.model, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 1 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from(""),
        Line::from("Local Model:").style(
            Style::default()
                .fg(TEXT_PRIMARY)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(vec![
            Span::styled(
                if focused == 2 { "  ▶ " } else { "    " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Provider: "),
            Span::styled(&wizard.local_provider, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 2 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                if focused == 3 { "  ▶ " } else { "    " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Model: "),
            Span::styled(&wizard.local_model, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 3 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from(vec![
            Span::styled(
                if focused == 4 { "  ▶ " } else { "    " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("URL: "),
            Span::styled(&wizard.local_url, Style::default().fg(NEON_GREEN)),
            Span::styled(
                if focused == 4 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
        ]),
        Line::from(""),
        Line::from("Navigation:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  Enter - Next step  |  ESC - Cancel").style(Style::default().fg(TEXT_DIM)),
    ];

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}

fn render_step_3_system_prompt(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let prompt_preview = if wizard.system_prompt.is_empty() {
        "(type to add prompt)".to_string()
    } else {
        wizard.system_prompt.chars().take(200).collect::<String>()
    };

    let text = vec![
        Line::from(""),
        Line::from("Step 3: System Prompt").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from("Define the agent's behavior and personality.")
            .style(Style::default().fg(TEXT_PRIMARY)),
        Line::from(""),
        Line::from(vec![
            Span::styled("▶ ", Style::default().fg(CYBER_CYAN)),
            Span::raw("Current Prompt: "),
            Span::styled("_", Style::default().fg(CYBER_CYAN)),
        ])
        .style(
            Style::default()
                .fg(TEXT_PRIMARY)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from("┌────────────────────────────────────────────────┐")
            .style(Style::default().fg(TEXT_MUTED)),
        Line::from(format!("│ {}│", prompt_preview)).style(Style::default().fg(NEON_GREEN)),
        Line::from("└────────────────────────────────────────────────┘")
            .style(Style::default().fg(TEXT_MUTED)),
        Line::from(""),
        Line::from(format!("Characters: {}", wizard.system_prompt.len()))
            .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from("Examples:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  • You are a helpful coding assistant").style(Style::default().fg(TEXT_DIM)),
        Line::from("  • You are an expert data analyst").style(Style::default().fg(TEXT_DIM)),
        Line::from("  • You are a creative writing partner").style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from("Navigation:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  Enter - Next step  |  ESC - Cancel").style(Style::default().fg(TEXT_DIM)),
    ];

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}

fn render_step_4_parameters(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let focused = wizard.focused_field;

    let text = vec![
        Line::from(""),
        Line::from("Step 4: Parameters").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from("Fine-tune the model's behavior.").style(Style::default().fg(TEXT_PRIMARY)),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                if focused == 0 { "▶ " } else { "  " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Temperature: "),
            Span::styled(
                format!("{:.2}", wizard.temperature),
                Style::default().fg(NEON_GREEN),
            ),
            Span::styled(
                if focused == 0 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("  (0.0 = focused, 2.0 = creative)"),
        ])
        .style(Style::default().fg(TEXT_PRIMARY)),
        Line::from(""),
        Line::from(vec![
            Span::styled(
                if focused == 1 { "▶ " } else { "  " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("Max Tokens: "),
            Span::styled(
                format!("{}", wizard.max_tokens),
                Style::default().fg(NEON_GREEN),
            ),
            Span::styled(
                if focused == 1 { "_" } else { "" },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::raw("  (1-100000)"),
        ])
        .style(Style::default().fg(TEXT_PRIMARY)),
        Line::from(""),
        Line::from(vec![
            Span::raw("Top P: "),
            Span::styled(
                format!("{:.2}", wizard.top_p),
                Style::default().fg(TEXT_DIM),
            ),
            Span::raw("  (0.0-1.0, nucleus sampling)"),
        ])
        .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from(vec![
            Span::raw("Frequency Penalty: "),
            Span::styled(
                format!("{:.2}", wizard.frequency_penalty),
                Style::default().fg(TEXT_DIM),
            ),
            Span::raw("  (-2.0 to 2.0)"),
        ])
        .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from(vec![
            Span::raw("Presence Penalty: "),
            Span::styled(
                format!("{:.2}", wizard.presence_penalty),
                Style::default().fg(TEXT_DIM),
            ),
            Span::raw("  (-2.0 to 2.0)"),
        ])
        .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from("Navigation:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  Enter - Next step  |  ESC - Cancel").style(Style::default().fg(TEXT_DIM)),
    ];

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}

fn render_step_5_tools(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let selected_count = wizard.selected_tools.len();
    let available_count = wizard.available_tools.len();
    let focused = wizard.focused_field;

    let mut text = vec![
        Line::from(""),
        Line::from("Step 5: Tools Selection").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from(format!(
            "Selected: {} / {} tools",
            selected_count, available_count
        ))
        .style(Style::default().fg(CYBER_CYAN)),
        Line::from(""),
        Line::from("Available Tools:").style(
            Style::default()
                .fg(TEXT_PRIMARY)
                .add_modifier(Modifier::BOLD),
        ),
    ];

    for (i, tool) in wizard.available_tools.iter().enumerate() {
        let is_selected = wizard.selected_tools.contains(tool);
        let checkbox = if is_selected { "[✓]" } else { "[ ]" };
        let is_focused = i == focused;
        let style = if is_selected {
            Style::default().fg(NEON_GREEN)
        } else if is_focused {
            Style::default().fg(CYBER_CYAN)
        } else {
            Style::default().fg(TEXT_PRIMARY)
        };
        text.push(Line::from(vec![
            Span::styled(
                if is_focused { "▶ " } else { "  " },
                Style::default().fg(CYBER_CYAN),
            ),
            Span::styled(format!("{} ", checkbox), style),
            Span::styled(tool.clone(), style),
        ]));
    }

    text.extend(vec![
        Line::from(""),
        Line::from("Note: Use Space to toggle, ↑↓ to navigate")
            .style(Style::default().fg(TEXT_DIM)),
        Line::from(""),
        Line::from("Navigation:").style(Style::default().fg(TEXT_MUTED)),
        Line::from("  Enter - Next step  |  ESC - Cancel").style(Style::default().fg(TEXT_DIM)),
    ]);

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}

fn render_step_6_review(f: &mut Frame, area: Rect, wizard: &AgentBuilderState) {
    let provider = if wizard.use_local_model {
        "local"
    } else {
        &wizard.provider
    };
    let model = if wizard.use_local_model {
        &wizard.local_model
    } else {
        &wizard.model
    };

    let model_info_str = if wizard.use_local_model {
        format!("{} ({})", wizard.local_model, wizard.local_provider)
    } else {
        format!("{} ({})", wizard.model, wizard.provider)
    };

    let cost = calculate_cost(provider, model, wizard.max_tokens);
    let model_info = get_model_info(provider, model);

    let mut text = vec![
        Line::from(""),
        Line::from("Step 6: Review & Confirm").style(
            Style::default()
                .fg(BRAND_PURPLE)
                .add_modifier(Modifier::BOLD),
        ),
        Line::from(""),
        Line::from("✓ Configuration Complete - Ready to Create")
            .style(Style::default().fg(NEON_GREEN).bold()),
        Line::from(""),
        Line::from("═══════════════════════════════════════════════════")
            .style(Style::default().fg(TEXT_MUTED)),
        Line::from(""),
        Line::from("Basic Info:").style(Style::default().fg(CYBER_CYAN).bold()),
        Line::from(vec![
            Span::styled("  Name: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                &wizard.name,
                Style::default().fg(NEON_GREEN).add_modifier(Modifier::BOLD),
            ),
        ]),
        Line::from(vec![
            Span::styled("  Description: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                if wizard.description.is_empty() {
                    "(none)"
                } else {
                    wizard.description.as_str()
                },
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
        Line::from(""),
        Line::from("Model Configuration:").style(Style::default().fg(CYBER_CYAN).bold()),
        Line::from(vec![
            Span::styled("  Model: ", Style::default().fg(TEXT_DIM)),
            Span::styled(&model_info_str, Style::default().fg(TEXT_PRIMARY).bold()),
        ]),
        Line::from(vec![
            Span::styled("  Context Window: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("{} tokens", model_info.context_window),
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
        Line::from(vec![
            Span::styled("  Temperature: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("{:.2}", wizard.temperature),
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
        Line::from(vec![
            Span::styled("  Max Tokens: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("{}", wizard.max_tokens),
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
        Line::from(""),
        Line::from("Tools:").style(Style::default().fg(CYBER_CYAN).bold()),
        Line::from(vec![
            Span::styled("  ", Style::default()),
            Span::styled(
                if wizard.selected_tools.is_empty() {
                    "None selected".to_string()
                } else {
                    wizard.selected_tools.join(", ")
                },
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]),
    ];

    // Add cost estimate
    if !cost.is_free {
        text.push(Line::from(""));
        text.push(Line::from("Estimated Cost:").style(Style::default().fg(AMBER_WARN).bold()));
        text.push(Line::from(vec![
            Span::styled("  Per 1K tokens: ", Style::default().fg(TEXT_DIM)),
            Span::styled(
                format!("${:.4}", cost.cost_1k),
                Style::default().fg(TEXT_PRIMARY),
            ),
        ]));
    } else {
        text.push(Line::from(""));
        text.push(Line::from(vec![
            Span::styled("  ✓ ", Style::default().fg(NEON_GREEN)),
            Span::styled("FREE (Local Model)", Style::default().fg(NEON_GREEN).bold()),
        ]));
    }

    text.push(Line::from(""));
    text.push(
        Line::from("═══════════════════════════════════════════════════")
            .style(Style::default().fg(TEXT_MUTED)),
    );
    text.push(Line::from(""));
    text.push(Line::from(vec![
        Span::styled("Press ", Style::default().fg(TEXT_DIM)),
        Span::styled("Enter", Style::default().fg(NEON_GREEN).bold()),
        Span::styled(" to create this agent", Style::default().fg(TEXT_DIM)),
    ]));

    let paragraph = Paragraph::new(text)
        .wrap(Wrap { trim: false })
        .alignment(Alignment::Left);

    f.render_widget(paragraph, area);
}
