//! Interactive TUI dashboard for Rustelo Tools
//!
//! This integrates the full-featured dashboard from the original
//! rustelo-manager with all its advanced TUI capabilities including live
//! preview, file management, and comprehensive page generation features.

use std::collections::HashMap;
use std::path::PathBuf;

use anyhow::{Context, Result};

/// Helper function to translate manager keys
fn t_mgr(_lang: &str, key: &str) -> String {
    // Simplified translation - return the key for now
    // This would integrate with the actual i18n system
    key.to_string()
}

/// Helper function to translate with parameters
fn t_mgr_with_params(lang: &str, key: &str, params: &[(&str, &str)]) -> String {
    let mut text = t_mgr(lang, key);

    // Simple parameter substitution: {$param_name}
    for (param_key, param_value) in params {
        let placeholder = format!("{{${}}}", param_key);
        text = text.replace(&placeholder, param_value);
    }

    text
}

#[cfg(feature = "tui")]
/// Run the advanced TUI dashboard with full manager functionality
pub fn run_dashboard() -> Result<()> {
    use crate::manager::find_project_root;

    // Discover available languages from site structure
    let available_languages = discover_available_languages_from_site()?;

    // Auto-select language (default to first available or English)
    let lang = available_languages
        .first()
        .unwrap_or(&"en".to_string())
        .clone();

    // Load CLI translations
    let translations = load_cli_translations(&lang)?;

    // Find project root
    let project_root = find_project_root().context("Could not find project root")?;

    // Use the existing manager dashboard - it already has TUI with ASK/prompt panel
    let mut dashboard = crate::manager::dashboard::Dashboard::new(
        project_root,
        translations,
        lang.clone(),
        available_languages,
    )
    .context("Failed to create dashboard")?;

    match dashboard.run() {
        Ok(()) => Ok(()),
        Err(e)
            if e.to_string().contains("Device not configured")
                || e.to_string().contains("raw mode")
                || e.to_string().contains("terminal") =>
        {
            eprintln!("{}", t_mgr(&lang, "mgr-tui-fallback-warning"));
            run_basic_cli_fallback(&lang)
        }
        Err(e) => Err(e),
    }
}

#[cfg(not(feature = "tui"))]
/// Run the basic CLI dashboard when TUI features are not available
pub fn run_dashboard() -> Result<()> {
    use std::io::{self, Write};

    println!("🎛️ Rustelo Tools Dashboard (CLI Mode)");
    println!("TUI features not enabled. Build with --features tui for full interface.");
    println!("==========================");
    println!();

    loop {
        println!("📋 Available Actions:");
        println!("  1. 🔍 Analyze project structure");
        println!("  2. 🚀 Generate new component");
        println!("  3. 📄 Generate new page");
        println!("  4. 🛣️ Generate new route");
        println!("  5. 📊 View project status");
        println!("  6. ❌ Exit");
        println!();

        print!("Enter choice (1-6): ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        match input.trim() {
            "1" => handle_analyze()?,
            "2" => handle_generate_component()?,
            "3" => handle_generate_page()?,
            "4" => handle_generate_route()?,
            "5" => handle_project_status()?,
            "6" => {
                println!("👋 Goodbye!");
                break;
            }
            _ => {
                println!("❌ Invalid choice. Please enter 1-6.");
                continue;
            }
        }

        println!();
        println!("Press Enter to continue...");
        let mut _input = String::new();
        io::stdin().read_line(&mut _input)?;
    }

    Ok(())
}

/// Discover available languages using shared utilities
fn discover_available_languages_from_site() -> Result<Vec<String>> {
    // Use core-types language discovery
    let languages = rustelo_core_types::i18n::discover_available_languages();
    Ok(languages.iter().map(|lang| lang.code.clone()).collect())
}

/// Load CLI translations using shared utilities
fn load_cli_translations(lang: &str) -> Result<HashMap<String, String>> {
    // For now, return a simple map since we'll use shared translation functions
    // directly The actual translations will be loaded by the shared FTL system
    let mut basic_translations = HashMap::new();

    // Add some basic fallback translations
    basic_translations.insert("mgr-cli-title".to_string(), t_mgr(lang, "mgr-cli-title"));
    basic_translations.insert(
        "mgr-cli-description".to_string(),
        t_mgr(lang, "mgr-cli-description"),
    );

    Ok(basic_translations)
}

#[cfg(feature = "cli")]
fn handle_analyze() -> Result<()> {
    println!("🔍 Analyzing project...");

    // Use basic runtime analysis since comprehensive analysis is build-time only
    let info_path =
        std::env::var("SITE_INFO_PATH").unwrap_or_else(|_| "target/site_build/info".to_string());
    match super::commands::analyze_project_basic(&info_path) {
        Ok(_) => {
            println!("✅ Basic analysis complete! Check {}/", info_path);
            println!(
                "💡 For comprehensive analysis, run 'just build' to trigger build-time analysis"
            );
        }
        Err(e) => {
            println!("❌ Analysis failed: {}", e);
        }
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_generate_component() -> Result<()> {
    use std::io::{self, Write};

    print!("Component name: ");
    io::stdout().flush()?;

    let mut name = String::new();
    io::stdin().read_line(&mut name)?;
    let name = name.trim();

    if name.is_empty() {
        println!("❌ Component name cannot be empty");
        return Ok(());
    }

    println!("🧩 Generating component: {}", name);

    // Use the CLI command handler
    if let Err(e) = super::commands::generate_component_scaffolding(name, "basic") {
        println!("❌ Component generation failed: {}", e);
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_generate_page() -> Result<()> {
    use std::io::{self, Write};

    print!("Page name: ");
    io::stdout().flush()?;

    let mut name = String::new();
    io::stdin().read_line(&mut name)?;
    let name = name.trim();

    if name.is_empty() {
        println!("❌ Page name cannot be empty");
        return Ok(());
    }

    println!("📄 Generating page: {}", name);

    // Use the CLI command handler
    if let Err(e) = super::commands::generate_page_scaffolding(name, "basic") {
        println!("❌ Page generation failed: {}", e);
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_generate_route() -> Result<()> {
    use std::io::{self, Write};

    print!("Route path: ");
    io::stdout().flush()?;

    let mut path = String::new();
    io::stdin().read_line(&mut path)?;
    let path = path.trim();

    if path.is_empty() {
        println!("❌ Route path cannot be empty");
        return Ok(());
    }

    println!("🛣️ Generating route: {}", path);

    // Use the CLI command handler
    if let Err(e) = super::commands::generate_route_scaffolding(path, "basic") {
        println!("❌ Route generation failed: {}", e);
    }

    Ok(())
}

#[cfg(feature = "cli")]
fn handle_project_status() -> Result<()> {
    println!("📊 Project Status");
    println!("================");

    // Get dynamic paths
    let info_path =
        std::env::var("SITE_INFO_PATH").unwrap_or_else(|_| "target/site_build/info".to_string());
    let templates_path =
        std::env::var("SITE_TEMPLATES_PATH").unwrap_or_else(|_| "site/templates".to_string());
    let site_root = std::env::var("SITE_ROOT_PATH").unwrap_or_else(|_| "site".to_string());

    // Check if key directories exist
    let directories = [
        ("src/", "Source code"),
        ("target/", "Build artifacts"),
        (site_root.as_str(), "Site content"),
        (templates_path.as_str(), "Templates"),
        (info_path.as_str(), "Generated documentation"),
    ];

    for (dir, desc) in &directories {
        let status = if std::path::Path::new(dir).exists() {
            "✅"
        } else {
            "❌"
        };
        println!("  {} {} ({})", status, desc, dir);
    }

    // Check if key files exist
    let files = [
        ("Cargo.toml", "Project manifest"),
        ("justfile", "Task runner"),
        (".gitignore", "Git ignore rules"),
    ];

    println!();
    for (file, desc) in &files {
        let status = if std::path::Path::new(file).exists() {
            "✅"
        } else {
            "❌"
        };
        println!("  {} {} ({})", status, desc, file);
    }

    // Git status
    println!();
    println!("📋 Git Status:");
    let git_output = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .output();

    match git_output {
        Ok(output) => {
            let stdout = String::from_utf8_lossy(&output.stdout);
            if stdout.trim().is_empty() {
                println!("  ✅ Working directory clean");
            } else {
                println!("  📝 {} files modified/untracked", stdout.lines().count());
            }
        }
        Err(_) => {
            println!("  ❌ Not a git repository");
        }
    }

    Ok(())
}

/// Basic CLI fallback when TUI mode fails
fn run_basic_cli_fallback(_lang: &str) -> Result<()> {
    use std::io::{self, Write};

    println!("🎛️ Rustelo Tools Dashboard (CLI Fallback Mode)");
    println!("================================================");
    println!();

    loop {
        println!("📋 Available Actions:");
        println!("  1. 🔍 Analyze project structure");
        println!("  2. 🚀 Generate new component");
        println!("  3. 📄 Generate new page");
        println!("  4. 🛣️ Generate new route");
        println!("  5. 📊 View project status");
        println!("  6. ❌ Exit");
        println!();

        print!("Enter choice (1-6): ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        match input.trim() {
            "1" => handle_analyze()?,
            "2" => handle_generate_component()?,
            "3" => handle_generate_page()?,
            "4" => handle_generate_route()?,
            "5" => handle_project_status()?,
            "6" => {
                println!("👋 Goodbye!");
                break;
            }
            _ => {
                println!("❌ Invalid choice. Please enter 1-6.");
                continue;
            }
        }

        println!();
        println!("Press Enter to continue...");
        let mut _input = String::new();
        io::stdin().read_line(&mut _input)?;
    }

    Ok(())
}

#[cfg(not(feature = "cli"))]
fn handle_analyze() -> Result<()> {
    Ok(())
}
#[cfg(not(feature = "cli"))]
fn handle_generate_component() -> Result<()> {
    Ok(())
}
#[cfg(not(feature = "cli"))]
fn handle_generate_page() -> Result<()> {
    Ok(())
}
#[cfg(not(feature = "cli"))]
fn handle_generate_route() -> Result<()> {
    Ok(())
}
#[cfg(not(feature = "cli"))]
fn handle_project_status() -> Result<()> {
    Ok(())
}
