//! Dashboard action execution
//!
//! Handles execution of dashboard menu actions including
//! system commands, built-in tools, and external processes.

use std::collections::HashMap;
use std::path::Path;

use anyhow::Result;

use super::state::{DashboardMode, DashboardState};

/// Execute a dashboard action command
pub fn execute_action(
    command: &str,
    project_root: &Path,
    state: &mut DashboardState,
    translations: &HashMap<String, String>,
) -> Result<()> {
    state.clear_messages();
    state.set_status(format!("Executing: {}", command));

    match command {
        // Built-in dashboard commands
        "quit" => {
            state.should_quit = true;
        }
        "show_help" => {
            state.mode = DashboardMode::Help;
        }
        "show_settings" => {
            state.mode = DashboardMode::Settings;
        }
        "refresh_dashboard" => {
            refresh_dashboard_data(state)?;
        }

        // Content management commands
        "page_generator" => {
            execute_page_generator(project_root, state, translations)?;
        }
        "content_editor" => {
            execute_content_editor(project_root, state, translations)?;
        }
        "translation_manager" => {
            execute_translation_manager(project_root, state)?;
        }
        "content_preview" => {
            execute_content_preview(project_root, state)?;
        }

        // Development tool commands
        "browser_logger" => {
            execute_browser_logger(project_root, state)?;
        }
        "api_explorer" => {
            execute_api_explorer(project_root, state)?;
        }
        "system_info" => {
            execute_system_info(project_root, state)?;
        }
        "route_inspector" => {
            execute_route_inspector(project_root, state)?;
        }
        "config_manager" => {
            execute_config_manager(project_root, state)?;
        }
        "deployment_status" => {
            execute_deployment_status(project_root, state)?;
        }

        // Shell commands (just commands)
        cmd if cmd.starts_with("just ") => {
            execute_shell_command(cmd, project_root, state)?;
        }

        // Unknown command
        _ => {
            state.set_error(format!("Unknown command: {}", command));
        }
    }

    Ok(())
}

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

/// Execute page generator (switch to integrated mode)
fn execute_page_generator(
    project_root: &Path,
    state: &mut DashboardState,
    translations: &HashMap<String, String>,
) -> Result<()> {
    state.set_status("Opening page generator...".to_string());

    // Switch to integrated page generator mode (this initializes the App)
    match state.enter_page_generator(project_root, translations) {
        Ok(()) => {
            state.set_status(
                "Page generator ready! Use Tab to navigate, Enter to select.".to_string(),
            );
        }
        Err(e) => {
            state.set_error(format!("Failed to initialize page generator: {}", e));
        }
    }

    Ok(())
}

/// Execute content editor (show page selector first)
fn execute_content_editor(
    project_root: &Path,
    state: &mut DashboardState,
    _translations: &HashMap<String, String>,
) -> Result<()> {
    // Show page selector to choose which page to edit
    state.set_status("Loading available pages...".to_string());

    match state.enter_page_selector(project_root) {
        Ok(()) => {
            if state.available_pages.is_empty() {
                state.set_error(
                    "No pages found to edit. Create a page first using page generator.".to_string(),
                );
            } else {
                state.set_status(
                    "Select a page to edit using ↑↓ arrows, Enter to select.".to_string(),
                );
            }
        }
        Err(e) => {
            state.set_error(format!("Failed to load pages: {}", e));
        }
    }

    Ok(())
}

/// Execute translation manager
fn execute_translation_manager(project_root: &Path, state: &mut DashboardState) -> Result<()> {
    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 locales_dir = project_root.join(&i18n_path).join("locales");

    let mut translation_info = String::from("Translation Manager\n\n");

    if locales_dir.exists() {
        translation_info.push_str(&format!("Locales directory: {}\n\n", locales_dir.display()));

        if let Ok(entries) = std::fs::read_dir(&locales_dir) {
            translation_info.push_str("Available languages:\n");
            for entry in entries.flatten() {
                if entry.path().is_dir() {
                    let lang_code = entry.file_name().to_string_lossy().to_string();
                    translation_info.push_str(&format!(
                        "• {} ({})\n",
                        lang_code,
                        get_language_name(&lang_code)
                    ));
                }
            }
        }
    } else {
        translation_info.push_str(&format!(
            "❌ Locales directory not found: {}\n",
            locales_dir.display()
        ));
    }

    translation_info.push_str(
        "\n\n🌍 Translation Management:\n• Edit FTL files for each language\n• Manage UI strings \
         and content\n• Validate translation keys\n• Sync translations across languages\n\n💡 To \
         edit translations manually:\n1. Navigate to site/i18n/locales/[lang]/\n2. Edit .ftl \
         files with any text editor\n3. Use dashboard F12 to test language switching\n\nPress Esc \
         to return to dashboard",
    );
    state.set_action_result(translation_info);
    Ok(())
}

/// Execute content preview
fn execute_content_preview(_project_root: &Path, state: &mut DashboardState) -> Result<()> {
    state.set_action_result(
        "🌐 Content Preview Server\n\n\
         📋 Features:\n\
         ✅ Hot reloading - Changes update instantly\n\
         ✅ Multi-device preview - Test on mobile/desktop\n\
         ✅ Content editing interface - Live editing\n\
         ✅ Real-time updates - See changes immediately\n\n\
         🚀 Launch Commands:\n\
         • Development: just dev\n\
         • CSS Watch: just css-watch\n\
         • Full Stack: just dev & just css-watch\n\n\
         🌍 Server Access:\n\
         • Local: http://localhost:3030\n\
         • Network: http://[your-ip]:3030\n\n\
         ⚡ Quick Start:\n\
         1. Run 'just dev' to start server\n\
         2. Open browser to localhost:3030\n\
         3. Edit content files for live updates\n\n\
         Press Esc to return to dashboard"
            .to_string(),
    );
    Ok(())
}

/// Execute browser logger
fn execute_browser_logger(project_root: &Path, state: &mut DashboardState) -> Result<()> {
    let script_path = project_root.join("scripts/browser-logs/collect-single-page.sh");

    if script_path.exists() {
        state.set_action_result(format!(
            "🔍 Browser Log Collector\n\n📁 Script Location: {}\n\n🛠️ What This Tool Does:\n✅ \
             Opens Chrome with specific page\n✅ Waits for page hydration\n✅ Collects console \
             logs and errors\n✅ Captures network error details\n✅ Creates timestamped log \
             files\n\n💻 Usage Examples:\n• ./collect-single-page.sh / (home page)\n• \
             ./collect-single-page.sh /contact\n• ./collect-single-page.sh /about\n• \
             ./collect-single-page.sh /es/inicio\n\n📋 What You Get:\n• \
             browser-log-[page]-[timestamp].log\n• Ready for Claude Code MCP tools\n• Console \
             errors and network issues\n\n⚡ Quick Steps:\n1. Start dev server: just dev\n2. Run \
             script with page path\n3. Use MCP tools in Claude Code\n\nPress Esc to return to \
             dashboard",
            script_path.display()
        ));
    } else {
        state.set_error(format!(
            "❌ Browser log script not found: {}\n\nExpected location: {}\n\nTo fix:\n1. Check if \
             scripts/browser-logs/ directory exists\n2. Verify collect-single-page.sh script is \
             present\n3. Ensure script has execute permissions",
            script_path.display(),
            script_path.display()
        ));
    }
    Ok(())
}

/// Execute API explorer
fn execute_api_explorer(_project_root: &Path, state: &mut DashboardState) -> Result<()> {
    state.set_action_result(
        "API Explorer\n\n\
         Available API endpoints:\n\
         • GET /api/health - Health check\n\
         • GET /api/content/* - Content API\n\
         • GET /api/routes - Route information\n\
         • GET /api/translations - Translation data\n\n\
         Development server: http://localhost:3030\n\n\
         [Implementation pending - will show interactive API browser]"
            .to_string(),
    );
    Ok(())
}

/// Execute system info
fn execute_system_info(project_root: &Path, state: &mut DashboardState) -> Result<()> {
    let mut info = String::from("System Information\n\n");

    // Project info
    info.push_str(&format!("Project Root: {}\n", project_root.display()));

    // Environment variables
    info.push_str("\nSite Environment:\n");
    let env_vars = [
        "SITE_ROOT_PATH",
        "SITE_SERVER_ROOT_CONTENT",
        "SITE_CONFIG_PATH",
        "SITE_UI_PATH",
        "SITE_I18N_PATH",
        "SITE_ASSETS_PATH",
    ];

    for var in &env_vars {
        if let Ok(value) = std::env::var(var) {
            info.push_str(&format!("• {}: {}\n", var, value));
        } else {
            info.push_str(&format!("• {}: (not set)\n", var));
        }
    }

    // Terminal info
    info.push_str(&format!(
        "\nTerminal Size: {}x{}\n",
        state.terminal_size.0, state.terminal_size.1
    ));

    state.set_action_result(info);
    Ok(())
}

/// Execute route inspector
fn execute_route_inspector(project_root: &Path, state: &mut DashboardState) -> Result<()> {
    let site_root = std::env::var("SITE_ROOT_PATH").unwrap_or_else(|_| "site".to_string());
    let config_path =
        std::env::var("SITE_CONFIG_PATH").unwrap_or_else(|_| format!("{}/config", site_root));
    let routes_dir = project_root.join(&config_path).join("routes");

    let mut route_info = String::from("Route Inspector\n\n");

    if routes_dir.exists() {
        route_info.push_str(&format!("Routes directory: {}\n\n", routes_dir.display()));

        if let Ok(entries) = std::fs::read_dir(&routes_dir) {
            route_info.push_str("Route files:\n");
            for entry in entries.flatten() {
                if entry.path().extension().is_some_and(|ext| ext == "toml") {
                    let file_name = entry.file_name().to_string_lossy().to_string();
                    route_info.push_str(&format!("• {}\n", file_name));
                }
            }
        }
    } else {
        route_info.push_str(&format!(
            "❌ Routes directory not found: {}\n",
            routes_dir.display()
        ));
    }

    route_info.push_str("\n[Implementation pending - will show route validation]");
    state.set_action_result(route_info);
    Ok(())
}

/// Execute config manager
fn execute_config_manager(_project_root: &Path, state: &mut DashboardState) -> Result<()> {
    state.set_action_result(
        "Configuration Manager\n\nConfiguration files:\n• Cargo.toml - Rust workspace \
         configuration\n• config.toml - Application configuration\n• site/config/* - Site \
         configuration files\n• .env - Environment variables\n\n[Implementation pending - will \
         launch config editor]"
            .to_string(),
    );
    Ok(())
}

/// Execute deployment status
fn execute_deployment_status(_project_root: &Path, state: &mut DashboardState) -> Result<()> {
    state.set_action_result(
        "Deployment Status\n\nBuild Status: ✅ Ready\nTests: ✅ Passing\nQuality Checks: ✅ \
         Passing\nDependencies: ✅ Up to date\n\nAvailable commands:\n• just build-prod - \
         Production build\n• just test - Run tests\n• just quality - Quality \
         checks\n\n[Implementation pending - will show real status]"
            .to_string(),
    );
    Ok(())
}

/// Show shell command information (no execution to prevent UI hanging)
fn execute_shell_command(
    command: &str,
    _project_root: &Path,
    state: &mut DashboardState,
) -> Result<()> {
    if command.trim().is_empty() {
        state.set_error("Empty command".to_string());
        return Ok(());
    }

    // Instead of executing, show command information
    let command_info = match command {
        cmd if cmd.starts_with("just dev") => {
            "🌐 Development Server\n\n\
             📋 What this does:\n\
             ✅ Starts Leptos development server\n\
             ✅ Enables hot reloading for Rust code\n\
             ✅ Serves on http://localhost:3030\n\
             ✅ Watches for file changes\n\n\
             💻 To run manually:\n\
             just dev\n\n\
             🔄 Alternative commands:\n\
             • cargo leptos watch\n\
             • cargo leptos serve\n\n\
             Press Esc to return to dashboard"
        }
        cmd if cmd.starts_with("just css-watch") => {
            "🎨 CSS Watch Mode\n\n\
             📋 What this does:\n\
             ✅ Watches CSS files for changes\n\
             ✅ Rebuilds CSS automatically\n\
             ✅ Uses UnoCSS for utility classes\n\
             ✅ Hot reloads styles in browser\n\n\
             💻 To run manually:\n\
             just css-watch\n\n\
             🔄 Alternative commands:\n\
             • npm run watch:css\n\
             • npm run build:css\n\n\
             Press Esc to return to dashboard"
        }
        cmd if cmd.starts_with("just build-prod") => {
            "📦 Production Build\n\n\
             📋 What this does:\n\
             ✅ Optimizes Rust code for production\n\
             ✅ Minifies JavaScript and CSS\n\
             ✅ Builds WebAssembly with optimizations\n\
             ✅ Creates deployment-ready artifacts\n\n\
             💻 To run manually:\n\
             just build-prod\n\n\
             🔄 Alternative commands:\n\
             • cargo leptos build --release\n\
             • LEPTOS_OUTPUT_NAME=website cargo leptos build\n\n\
             Press Esc to return to dashboard"
        }
        cmd if cmd.starts_with("just test") => {
            "🧪 Test Execution\n\n\
             📋 What this does:\n\
             ✅ Runs all Rust unit tests\n\
             ✅ Runs integration tests\n\
             ✅ Tests both client and server code\n\
             ✅ Generates test coverage reports\n\n\
             💻 To run manually:\n\
             just test\n\n\
             🔄 Alternative commands:\n\
             • cargo test\n\
             • cargo test --all\n\n\
             Press Esc to return to dashboard"
        }
        cmd if cmd.starts_with("just quality") => {
            "✅ Quality Checks\n\n\
             📋 What this does:\n\
             ✅ Runs cargo fmt (code formatting)\n\
             ✅ Runs cargo clippy (linting)\n\
             ✅ Runs security audit\n\
             ✅ Checks for code quality issues\n\n\
             💻 To run manually:\n\
             just quality\n\n\
             🔄 Alternative commands:\n\
             • just fmt\n\
             • cargo clippy\n\
             • cargo audit\n\n\
             Press Esc to return to dashboard"
        }
        cmd if cmd.starts_with("just fm") => {
            "✨ Code Formatting\n\n\
             📋 What this does:\n\
             ✅ Formats Rust code with rustfmt\n\
             ✅ Applies consistent style rules\n\
             ✅ Fixes indentation and spacing\n\
             ✅ Ensures code consistency\n\n\
             💻 To run manually:\n\
             just fm\n\n\
             🔄 Alternative commands:\n\
             • cargo fmt\n\
             • cargo fmt --all\n\n\
             Press Esc to return to dashboard"
        }
        _ => &format!(
            "🖥️ Shell Command\n\n\
                     📋 Command to run:\n\
                     {}\n\n\
                     💻 To execute manually:\n\
                     Open terminal and run:\n\
                     {}\n\n\
                     ⚠️ Note: Commands are not executed from dashboard\n\
                     to prevent UI hanging and maintain stability.\n\n\
                     Press Esc to return to dashboard",
            command, command
        ),
    };

    state.set_action_result(command_info.to_string());
    Ok(())
}

/// Get human-readable language name
fn get_language_name(code: &str) -> &'static str {
    match code {
        "en" => "English",
        "es" => "Spanish",
        "fr" => "French",
        "de" => "German",
        "it" => "Italian",
        "pt" => "Portuguese",
        "ja" => "Japanese",
        "zh" => "Chinese",
        "ru" => "Russian",
        _ => "Unknown",
    }
}
