//! Rustelo Dashboard System
//!
//! A comprehensive TUI dashboard for Rustelo development workflow.
//! Provides menu-driven access to all development tasks and utilities.

pub mod actions;
pub mod config;
pub mod state;
pub mod ui;

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
// Removed unused imports
pub use config::{DashboardConfig, MenuAction, MenuCategory, QuickAction};
pub use state::{DashboardMode, DashboardState};

use crate::manager::ui::SafeTerminal;
use crate::utils::RouteMetadataAccess;

/// Main dashboard application
pub struct Dashboard {
    pub state: DashboardState,
    pub config: DashboardConfig,
    pub translations: HashMap<String, String>,
    pub project_root: PathBuf,
}

impl Dashboard {
    /// Create new dashboard instance
    pub fn new(
        project_root: PathBuf,
        translations: HashMap<String, String>,
        current_language: String,
        available_languages: Vec<String>,
    ) -> Result<Self> {
        let mut config = DashboardConfig::load(&project_root)
            .context("Failed to load dashboard configuration")?;

        // Load dashboard-specific translations and apply them to config
        let dashboard_translations =
            Self::load_dashboard_translations(&project_root, &current_language)?;
        let mut all_translations = translations.clone();
        all_translations.extend(dashboard_translations);
        config.apply_translations(&all_translations);

        let state = DashboardState::new(&config, current_language, available_languages);

        Ok(Self {
            state,
            config,
            translations: all_translations,
            project_root,
        })
    }

    /// Load dashboard-specific translations from FTL files
    fn load_dashboard_translations(
        project_root: &Path,
        language: &str,
    ) -> Result<HashMap<String, String>> {
        let site_root = std::env::var("SITE_ROOT_PATH").unwrap_or_else(|_| "site".to_string());
        let i18n_path =
            std::env::var("SITE_I18N_PATH").unwrap_or_else(|_| format!("{}/i18n", site_root));

        let dashboard_ftl_path = project_root
            .join(&i18n_path)
            .join("locales")
            .join(language)
            .join("manager")
            .join("dashboard.ftl");

        if !dashboard_ftl_path.exists() {
            // Return empty translations if dashboard.ftl doesn't exist
            return Ok(HashMap::new());
        }

        let ftl_content = std::fs::read_to_string(&dashboard_ftl_path).with_context(|| {
            format!(
                "Failed to read dashboard translations: {}",
                dashboard_ftl_path.display()
            )
        })?;

        // Simple FTL parser - extract key = value pairs
        let mut translations = HashMap::new();
        for line in ftl_content.lines() {
            let line = line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }

            if let Some((key, value)) = line.split_once(" = ") {
                translations.insert(key.trim().to_string(), value.trim().to_string());
            }
        }

        Ok(translations)
    }

    /// Run the main dashboard loop
    pub fn run(&mut self) -> Result<()> {
        let mut terminal = SafeTerminal::new().context("Failed to setup terminal")?;

        eprintln!("🚀 DEBUG: Starting dashboard main loop");
        while !self.state.should_quit {
            // Render dashboard UI
            terminal
                .draw(|frame| {
                    ui::render_dashboard(frame, &self.state, &self.config, &self.translations);
                })
                .context("Failed to render dashboard")?;

            // Handle user input
            self.handle_input().context("Failed to handle input")?;
        }
        eprintln!("🛑 DEBUG: Main loop exited - should_quit is true");

        Ok(())
    }

    /// Handle user input events
    fn handle_input(&mut self) -> Result<()> {
        use std::time::Duration;

        use crossterm::event::{poll, read};

        // Poll for events with a timeout to prevent hanging
        if poll(Duration::from_millis(100)).context("Failed to poll for events")? {
            match read().context("Failed to read event")? {
                crossterm::event::Event::Key(key) => {
                    self.handle_key_event(key)?;
                }
                crossterm::event::Event::Resize(width, height) => {
                    self.state.terminal_size = (width, height);
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Handle keyboard events
    fn handle_key_event(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
        use crossterm::event::{KeyCode, KeyModifiers};

        // Handle page generator, editor, and selector modes first
        match self.state.mode {
            DashboardMode::PageGenerator => {
                return self.handle_page_generator_input(key);
            }
            DashboardMode::PageEditor => {
                return self.handle_page_editor_input(key);
            }
            DashboardMode::PageSelector => {
                return self.handle_page_selector_input(key);
            }
            _ => {}
        }

        match key.code {
            KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.state.should_quit = true;
            }
            KeyCode::Esc => {
                if self.state.chat_focused {
                    self.state.toggle_chat_focus();
                } else if matches!(
                    self.state.mode,
                    DashboardMode::PageGenerator
                        | DashboardMode::PageEditor
                        | DashboardMode::PageSelector
                ) {
                    self.state.exit_page_mode();
                } else if self.state.mode != DashboardMode::Main {
                    self.state.mode = DashboardMode::Main;
                } else {
                    self.state.should_quit = true;
                }
            }
            KeyCode::Up => {
                self.state.move_selection(-1);
            }
            KeyCode::Down => {
                self.state.move_selection(1);
            }
            KeyCode::Left => {
                self.state.move_category(-1, self.config.category_count());
            }
            KeyCode::Right => {
                self.state.move_category(1, self.config.category_count());
            }
            KeyCode::Tab => {
                if !self.state.chat_focused {
                    if key.modifiers.contains(KeyModifiers::SHIFT) {
                        // Shift-Tab: go to previous category
                        self.state.prev_category(self.config.category_count());
                    } else {
                        // Tab: go to next category
                        self.state.next_category(self.config.category_count());
                    }
                } else {
                    // If chat focused, Tab/Shift-Tab should unfocus chat
                    self.state.toggle_chat_focus();
                }
            }
            KeyCode::BackTab => {
                // BackTab is another way to handle Shift-Tab
                if !self.state.chat_focused {
                    self.state.prev_category(self.config.category_count());
                } else {
                    self.state.toggle_chat_focus();
                }
            }
            KeyCode::Enter => {
                if self.state.chat_focused {
                    let chat_input = self.state.submit_chat();
                    self.handle_chat_input(chat_input)?;
                } else {
                    self.execute_selected_action()?;
                }
            }
            KeyCode::Backspace => {
                if self.state.chat_focused {
                    self.state.chat_backspace();
                }
            }
            KeyCode::Char(c) => {
                if self.state.chat_focused {
                    self.state.chat_input_char(c);
                } else if c == '/' || c == ':' {
                    // Quick way to start typing in chat (/ or :)
                    self.state.toggle_chat_focus();
                } else if c == ' ' {
                    // Spacebar to toggle between categories and actions focus
                    self.state.toggle_panel_focus();
                } else {
                    self.handle_shortcut(c)?;
                }
            }
            KeyCode::F(5) => {
                self.refresh_dashboard()?;
            }
            KeyCode::F(12) => {
                // F12 to switch language
                if self.state.next_language() {
                    // Reload dashboard translations for new language
                    match Self::load_dashboard_translations(
                        &self.project_root,
                        &self.state.current_language,
                    ) {
                        Ok(dashboard_translations) => {
                            // Update config with new translations
                            self.config.apply_translations(&dashboard_translations);
                            self.state.set_status(format!(
                                "Switched to language: {} ({})",
                                self.state.current_language.to_uppercase(),
                                match self.state.current_language.as_str() {
                                    "en" => "English",
                                    "es" => "Español",
                                    _ => "Unknown",
                                }
                            ));
                        }
                        Err(e) => {
                            self.state.set_error(format!(
                                "Language switched but translation loading failed: {}",
                                e
                            ));
                        }
                    }
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Execute the currently selected action
    fn execute_selected_action(&mut self) -> Result<()> {
        let action = self.state.get_selected_action(&self.config);
        if let Some(action) = action {
            actions::execute_action(
                &action.command,
                &self.project_root,
                &mut self.state,
                &self.translations,
            )?;
        }
        Ok(())
    }

    /// Handle keyboard shortcuts
    fn handle_shortcut(&mut self, c: char) -> Result<()> {
        // Check quick actions first
        for quick_action in &self.config.quick_actions {
            if quick_action.shortcut == c.to_string() {
                actions::execute_action(
                    &quick_action.command,
                    &self.project_root,
                    &mut self.state,
                    &self.translations,
                )?;
                return Ok(());
            }
        }

        // Check category actions
        if let Some(category) = self.state.get_current_category(&self.config) {
            for action in &category.actions {
                if action.shortcut == c.to_string() {
                    actions::execute_action(
                        &action.command,
                        &self.project_root,
                        &mut self.state,
                        &self.translations,
                    )?;
                    return Ok(());
                }
            }
        }

        Ok(())
    }

    /// Handle chat input submission
    fn handle_chat_input(&mut self, input: String) -> Result<()> {
        if input.trim().is_empty() {
            return Ok(());
        }

        // Parse chat commands
        let input = input.trim();

        if input.starts_with('/') {
            // Handle slash commands
            match input {
                "/help" => {
                    self.state.mode = DashboardMode::Help;
                }
                "/settings" => {
                    self.state.mode = DashboardMode::Settings;
                }
                "/clear" => {
                    self.state.chat_history.clear();
                    self.state.set_status("Chat history cleared".to_string());
                }
                "/quit" => {
                    self.state.should_quit = true;
                }
                _ => {
                    self.state.set_error(format!("Unknown command: {}", input));
                }
            }
        } else if input.starts_with("e ") || input.starts_with("edit ") {
            // Handle edit commands: "e <page_name>" or "edit <page_name>"
            let parts: Vec<&str> = input.splitn(2, ' ').collect();
            if parts.len() == 2 {
                let page_name = parts[1].trim();
                if !page_name.is_empty() {
                    self.state
                        .set_status(format!("Searching for page: {}", page_name));
                    // Search for the page by name/canonical_path
                    match self.state.find_page_by_path(&self.project_root, page_name) {
                        Ok(Some((path, component))) => {
                            // Found the page! Open editor directly
                            match self.state.enter_page_editor(
                                &self.project_root,
                                &self.translations,
                                Some(component.clone()),
                            ) {
                                Ok(()) => {
                                    self.state.set_status(format!(
                                        "Editing page: {} ({})",
                                        path, component
                                    ));
                                }
                                Err(e) => {
                                    self.state.set_error(format!(
                                        "Failed to open editor for '{}': {}",
                                        page_name, e
                                    ));
                                }
                            }
                        }
                        Ok(None) => {
                            // Page not found in routes, fall back to page selector
                            match self.state.enter_page_selector(&self.project_root) {
                                Ok(()) => {
                                    self.state.set_status(format!(
                                        "'{}' not found in routes. Select page to edit from list.",
                                        page_name
                                    ));
                                }
                                Err(e) => {
                                    self.state
                                        .set_error(format!("Failed to open page selector: {}", e));
                                }
                            }
                        }
                        Err(e) => {
                            self.state.set_error(format!(
                                "Error searching for page '{}': {}",
                                page_name, e
                            ));
                        }
                    }
                } else {
                    self.state.set_error(
                        "Page name cannot be empty. Usage: e <page_name> or edit <page_name>"
                            .to_string(),
                    );
                }
            } else {
                self.state
                    .set_error("Usage: e <page_name> or edit <page_name>".to_string());
            }
        } else if input == "e" || input == "edit" {
            // Handle standalone 'e' or 'edit' commands - switch to page selector for
            // editing
            self.state
                .set_status("Opening page selector...".to_string());
            match self.state.enter_page_selector(&self.project_root) {
                Ok(()) => {
                    self.state.set_status(
                        "Select a page to edit using ↑↓ arrows, Enter to select.".to_string(),
                    );
                }
                Err(e) => {
                    self.state
                        .set_error(format!("Failed to open page selector: {}", e));
                }
            }
        } else {
            // Handle regular chat input (simulate AI response for now)
            let response = self.simulate_ai_response(input);
            self.state.set_action_result(format!(
                "💬 AI Assistant\n\nYou: {}\n\nAI: {}",
                input, response
            ));
        }

        Ok(())
    }

    /// Simulate AI response (placeholder for actual AI integration)
    fn simulate_ai_response(&self, input: &str) -> String {
        let input_lower = input.to_lowercase();

        if input_lower.contains("create") && input_lower.contains("page") {
            "I can help you create a new page! Use the 'Create New Page' action in the Content \
             Management category, or press 'n' to start the page generator wizard."
                .to_string()
        } else if input_lower.contains("edit") && input_lower.contains("page") {
            "I can help you edit pages! You can:\n• Type 'e' or 'edit' to open the page editor\n• \
             Type 'e <page_name>' to edit a specific page\n• Use the 'Edit Static Content' action \
             in Content Management"
                .to_string()
        } else if input_lower.contains("help") {
            "I'm your Rustelo development assistant. I can help with:\n• Creating and editing \
             pages (try 'e' or 'edit')\n• Managing content and translations\n• Running development \
             commands\n• System information and debugging\n\nQuick commands:\n• 'e' or 'edit' - \
             Launch page editor\n• 'e <name>' - Edit specific page\n• '/help' - Show keyboard \
             shortcuts"
                .to_string()
        } else if input_lower.contains("build") || input_lower.contains("compile") {
            "To build your project, you can:\n• Use 'just build' for development build\n• Use \
             'just build-prod' for production\n• Check the Build & Deploy category for more \
             options\n\nPress 'b' for quick production build!"
                .to_string()
        } else if input_lower.contains("test") {
            "For testing, try:\n• 'just test' - Run all tests\n• 'just quality' - Run quality \
             checks\n• Browser logs are available in Development Tools\n\nPress 'u' to run tests \
             quickly!"
                .to_string()
        } else if input_lower.contains("server") || input_lower.contains("dev") {
            "To start the development server:\n• Use 'just dev' for full dev server with hot \
             reload\n• Press 'd' for quick access\n• Check Development Tools for CSS watch and \
             browser logs"
                .to_string()
        } else {
            format!(
                "I understand you're asking about '{}'. While I'm still learning, you can explore \
                 the dashboard categories above or try specific commands like '/help' for more \
                 assistance!",
                input
            )
        }
    }

    /// Refresh dashboard data
    fn refresh_dashboard(&mut self) -> Result<()> {
        self.state.last_refresh = std::time::Instant::now();
        self.state.status_message = Some("Dashboard refreshed".to_string());
        Ok(())
    }

    /// Handle input when in page generator mode
    fn handle_page_generator_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
        use crossterm::event::{KeyCode, KeyModifiers};

        // Handle dashboard-specific keys first
        match key.code {
            KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.state.should_quit = true;
                return Ok(());
            }
            KeyCode::Esc => {
                // Let the page app handle Esc to exit properly, or exit if there's an issue
                if let Some(ref mut page_app) = self.state.page_app {
                    // Check if the app is in a state where it would quit on Esc
                    if !page_app.show_help
                        && matches!(
                            page_app.generation_state,
                            crate::manager::app::GenerationState::Form
                        )
                    {
                        self.state.exit_page_mode();
                        return Ok(());
                    }
                    // Otherwise, let the app handle Esc (e.g., close help)
                    crate::manager::input::handle_key_event(page_app, key)?;
                } else {
                    self.state.exit_page_mode();
                }
                return Ok(());
            }
            KeyCode::F(12) => {
                // F12 to switch language in page generator
                if self.state.next_language() {
                    // Reload dashboard translations for new language
                    match Self::load_dashboard_translations(
                        &self.project_root,
                        &self.state.current_language,
                    ) {
                        Ok(dashboard_translations) => {
                            self.translations = dashboard_translations;
                            // Also update the page app with new translations if available
                            if let Some(ref mut page_app) = self.state.page_app {
                                // Recreate translations for the page app
                                let new_translations = self.translations.clone();
                                page_app.translations = new_translations;
                                self.state.set_status(format!(
                                    "Language switched to {}",
                                    self.state.current_language.to_uppercase()
                                ));
                            }
                        }
                        Err(e) => {
                            self.state
                                .set_error(format!("Failed to reload translations: {}", e));
                        }
                    }
                }
                return Ok(());
            }
            _ => {}
        }

        // Forward all other input to the page generator app
        if let Some(ref mut page_app) = self.state.page_app {
            crate::manager::input::handle_key_event(page_app, key)?;

            // Check if the app has completed generation and should return to dashboard
            if let crate::manager::app::GenerationState::Success { .. } = &page_app.generation_state
            {
                // Give the user a moment to see the success message, then they
                // can press Esc Don't auto-exit, let them read
                // the result
            }
        }

        Ok(())
    }

    /// Handle input when in page editor mode
    fn handle_page_editor_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
        use crossterm::event::{KeyCode, KeyModifiers};

        // Handle dashboard-specific keys first, then forward others
        match key.code {
            KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.state.should_quit = true;
                return Ok(());
            }
            KeyCode::Esc => {
                // Go back to page selector instead of main dashboard
                match self.state.enter_page_selector(&self.project_root) {
                    Ok(()) => {
                        self.state
                            .set_status("Returned to page selector".to_string());
                    }
                    Err(e) => {
                        self.state
                            .set_error(format!("Failed to open page selector: {}", e));
                    }
                }
                return Ok(());
            }
            KeyCode::Char('q') => {
                // 'q' alone goes to main dashboard
                self.state.exit_page_mode();
                return Ok(());
            }
            KeyCode::Char(' ') => {
                // Space bar: Switch to next panel
                self.state.next_page_editor_panel();
                return Ok(());
            }
            KeyCode::BackTab => {
                // Shift+Tab: Switch to previous panel
                self.state.prev_page_editor_panel();
                return Ok(());
            }
            KeyCode::Up => {
                self.state.move_panel_item_selection(-1);
                return Ok(());
            }
            KeyCode::Down => {
                self.state.move_panel_item_selection(1);
                return Ok(());
            }
            KeyCode::Char('v') => {
                // View action - show selected item details
                self.handle_view_action();
                return Ok(());
            }
            KeyCode::Char('e') => {
                // Edit action - open in external editor with backup
                self.handle_edit_action();
                return Ok(());
            }
            KeyCode::Char('/') => {
                // Ask AI Assistant - same as main dashboard
                self.state.toggle_chat_focus();
                return Ok(());
            }
            KeyCode::Enter => {
                // Enter: Default to View action
                self.handle_view_action();
                return Ok(());
            }
            _ => {
                // Forward other input to page app if needed
                if let Some(ref mut page_app) = self.state.page_app {
                    crate::manager::input::handle_key_event(page_app, key)?;
                }
            }
        }

        Ok(())
    }

    /// Handle input when in page selector mode
    fn handle_page_selector_input(&mut self, key: crossterm::event::KeyEvent) -> Result<()> {
        use crossterm::event::{KeyCode, KeyModifiers};

        match key.code {
            KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.state.should_quit = true;
            }
            KeyCode::Esc => {
                self.state.exit_page_mode();
            }
            KeyCode::Up => {
                self.state.move_page_selection(-1);
            }
            KeyCode::Down => {
                self.state.move_page_selection(1);
            }
            KeyCode::Enter => {
                // Select the current page and switch to editor
                eprintln!("🔍 DEBUG: Enter pressed in page selector");
                eprintln!(
                    "🔍 DEBUG: Available pages count: {}",
                    self.state.available_pages.len()
                );
                eprintln!(
                    "🔍 DEBUG: Selected index: {}",
                    self.state.selected_page_index
                );
                eprintln!(
                    "🔍 DEBUG: Selected page: {:?}",
                    self.state.get_selected_page()
                );

                if let Err(e) = self
                    .state
                    .select_page_for_editing(&self.project_root, &self.translations)
                {
                    eprintln!("❌ DEBUG: select_page_for_editing failed: {}", e);
                    self.state
                        .set_error(format!("Failed to open page editor: {}", e));
                } else {
                    eprintln!("✅ DEBUG: Page editor opened successfully");
                    eprintln!("🔍 DEBUG: New mode: {:?}", self.state.mode);
                    self.state.set_status("Opening page editor...".to_string());
                }
            }
            _ => {}
        }

        Ok(())
    }

    /// Handle view action for selected item in page editor
    fn handle_view_action(&mut self) {
        use crate::manager::dashboard::state::PageEditorPanel;

        match self.state.page_editor_panel {
            PageEditorPanel::RouteConfig => {
                if let Some(ref config) = self.state.route_config_data {
                    // Parse the RouteConfigToml to get all available fields dynamically
                    if let Ok(toml_string) = toml::to_string(config) {
                        if let Ok(toml_value) = toml_string.parse::<toml::Value>() {
                            if let Some(routes_table) = toml_value.as_table() {
                                // Find the matching route entry
                                for (route_key, route_value) in routes_table {
                                    if let Some(route_table) = route_value.as_table() {
                                        if let Some(page_component) =
                                            route_table.get("page_component")
                                        {
                                            if let Some(component_str) = page_component.as_str() {
                                                if component_str == config.component.as_str() {
                                                    // Get all fields from this route entry
                                                    let mut field_list = Vec::new();
                                                    field_list.push((
                                                        route_key.clone(),
                                                        route_key.clone(),
                                                    ));

                                                    for (key, value) in route_table {
                                                        let value_str = match value {
                                                            toml::Value::String(s) => s.clone(),
                                                            toml::Value::Integer(i) => {
                                                                i.to_string()
                                                            }
                                                            toml::Value::Float(f) => f.to_string(),
                                                            toml::Value::Boolean(b) => {
                                                                b.to_string()
                                                            }
                                                            toml::Value::Array(arr) => {
                                                                format!("{:?}", arr)
                                                            }
                                                            _ => "Complex value".to_string(),
                                                        };
                                                        field_list.push((key.clone(), value_str));
                                                    }

                                                    if let Some((field_name, field_value)) =
                                                        field_list.get(
                                                            self.state.selected_panel_item_index,
                                                        )
                                                    {
                                                        self.state.set_action_result(format!(
                                                            "📋 Route Configuration - {}\n\n{}: \
                                                             {}\n\n[v] View | [e] Edit | [Space] \
                                                             Next Panel | [Esc] Back",
                                                            field_name, field_name, field_value
                                                        ));
                                                    } else {
                                                        self.state.set_action_result(
                                                            "📋 Route Configuration\n\nNo field \
                                                             selected"
                                                                .to_string(),
                                                        );
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                }
                            } else {
                                self.state.set_action_result(
                                    "📋 Route Configuration\n\nInvalid TOML structure".to_string(),
                                );
                            }
                        }
                    } else {
                        self.state.set_action_result(
                            "📋 Route Configuration\n\nFailed to parse TOML".to_string(),
                        );
                    }
                } else {
                    self.state.set_action_result(
                        "📋 Route Configuration\n\nNo route configuration found".to_string(),
                    );
                }
            }
            PageEditorPanel::I18nFiles => {
                if let Some((display_name, file_path)) = self
                    .state
                    .i18n_files
                    .get(self.state.selected_panel_item_index)
                {
                    self.state.set_action_result(format!(
                        "🌐 I18n File Preview\n\n{}\n{}\n\n[v] View | [e] Edit | [Space] Next \
                         Panel | [Esc] Back",
                        display_name, file_path
                    ));
                } else {
                    self.state.set_action_result(
                        "🌐 I18n Files\n\nNo files found or none selected".to_string(),
                    );
                }
            }
            PageEditorPanel::SourceFiles => {
                if let Some((display_name, file_path)) = self
                    .state
                    .source_files
                    .get(self.state.selected_panel_item_index)
                {
                    self.state.set_action_result(format!(
                        "🦀 Source File Preview\n\n{}\n{}\n\n[v] View | [e] Edit | [Space] Next \
                         Panel | [Esc] Back",
                        display_name, file_path
                    ));
                } else {
                    self.state.set_action_result(
                        "🦀 Source Files\n\nNo files found or none selected".to_string(),
                    );
                }
            }
            PageEditorPanel::EditorSelector => {
                let editors = ["VS Code", "Cursor", "System Default"];
                if let Some(editor_name) = editors.get(self.state.selected_panel_item_index) {
                    self.state.set_action_result(format!(
                        "🖥️  Editor Selection\n\nSelected: {}\n\n[v] View | [e] Set as Default | \
                         [Space] Next Panel | [Esc] Back",
                        editor_name
                    ));
                } else {
                    self.state.set_action_result(
                        "🖥️  Editor Selection\n\nNo editor selected".to_string(),
                    );
                }
            }
        }

        self.state.mode = DashboardMode::ActionResult;
    }

    /// Handle edit action for selected item in page editor
    fn handle_edit_action(&mut self) {
        use crate::manager::dashboard::state::PageEditorPanel;

        match self.state.page_editor_panel {
            PageEditorPanel::RouteConfig => {
                self.state.set_action_result(
                    "🚧 Edit Route Configuration\n\nRoute configuration editing not yet \
                     implemented.\nThis will allow editing TOML values with \
                     validation.\n\n[Space] Next Panel | [Esc] Back"
                        .to_string(),
                );
            }
            PageEditorPanel::I18nFiles => {
                if let Some((display_name, file_path)) = self
                    .state
                    .i18n_files
                    .get(self.state.selected_panel_item_index)
                    .cloned()
                {
                    // TODO: Create backup and launch editor
                    self.state.set_action_result(format!(
                        "📝 Opening I18n File in Editor\n\nFile: {}\nPath: {}\n\n🔄 Creating \
                         backup...\n📂 Launching editor...\n\n[Space] Next Panel | [Esc] Back",
                        display_name, file_path
                    ));
                } else {
                    self.state.set_action_result(
                        "🌐 I18n Files\n\nNo file selected for editing".to_string(),
                    );
                }
            }
            PageEditorPanel::SourceFiles => {
                if let Some((display_name, file_path)) = self
                    .state
                    .source_files
                    .get(self.state.selected_panel_item_index)
                    .cloned()
                {
                    // TODO: Create backup and launch editor
                    self.state.set_action_result(format!(
                        "📝 Opening Source File in Editor\n\nFile: {}\nPath: {}\n\n🔄 Creating \
                         backup...\n📂 Launching editor...\n\n[Space] Next Panel | [Esc] Back",
                        display_name, file_path
                    ));
                } else {
                    self.state.set_action_result(
                        "🦀 Source Files\n\nNo file selected for editing".to_string(),
                    );
                }
            }
            PageEditorPanel::EditorSelector => {
                let editors = ["VS Code", "Cursor", "System Default"];
                if let Some(editor_name) = editors.get(self.state.selected_panel_item_index) {
                    self.state.set_action_result(format!(
                        "🖥️  Editor Preference Updated\n\nDefault editor set to: {}\n\n✅ \
                         Configuration saved\n\n[Space] Next Panel | [Esc] Back",
                        editor_name
                    ));
                } else {
                    self.state.set_action_result(
                        "🖥️  Editor Selection\n\nNo editor selected".to_string(),
                    );
                }
            }
        }

        self.state.mode = DashboardMode::ActionResult;
    }
}
