//! Form with Autocompletion Integration
//!
//! This example demonstrates how to use autocompletion helpers with interactive forms.
//! It shows practical integration patterns for:
//! - Email addresses with pattern-based suggestions
//! - Username with history
//! - Country selection with filtering
//! - Website URLs with pattern guidance
//!
//! Run with: cargo run --example form_with_autocompletion

use typedialog_core::autocompletion::{FilterCompleter, HistoryCompleter, PatternCompleter, PatternType};
use typedialog_core::prelude::*;
use typedialog_core::prompts;

fn main() -> Result<()> {
    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║              User Registration with Autocompletion             ║");
    println!("╚════════════════════════════════════════════════════════════════╝\n");

    // Initialize completers for different fields
    let mut username_history = HistoryCompleter::new(5);
    let mut email_history = HistoryCompleter::new(10);

    // Pre-populate with previous entries (simulating loaded history)
    username_history.add("alice_smith".to_string());
    username_history.add("alice.smith".to_string());
    username_history.add("asmith2024".to_string());

    email_history.add("alice@company.com".to_string());
    email_history.add("alice.smith@example.org".to_string());
    email_history.add("alice@personal.com".to_string());

    // Country completer for quick filtering
    let countries = vec![
        "United States".to_string(),
        "Canada".to_string(),
        "Mexico".to_string(),
        "United Kingdom".to_string(),
        "Germany".to_string(),
        "France".to_string(),
        "Spain".to_string(),
        "Italy".to_string(),
        "Other".to_string(),
    ];
    let country_completer = FilterCompleter::new(countries.clone());

    // Email pattern for smart suggestions
    let mut email_pattern = PatternCompleter::new(PatternType::Email);
    email_pattern.add_suggestion("@company.com".to_string());
    email_pattern.add_suggestion("@company.org".to_string());

    // URL pattern for website input
    let url_pattern = PatternCompleter::new(PatternType::Url);

    // ============================================================
    // SECTION 1: USERNAME INPUT WITH HISTORY
    // ============================================================
    println!("📋 SECTION 1: Account Information\n");

    println!("💡 Available usernames (from history):");
    for (i, name) in username_history.get_history().iter().enumerate() {
        println!("   {}. {}", i + 1, name);
    }
    println!();

    let username = prompts::text(
        "Enter username (start typing to see suggestions)",
        None,
        None,
    )?;

    // Add to history for future sessions
    username_history.add(username.clone());

    println!("✓ Username: {}\n", username);

    // ============================================================
    // SECTION 2: EMAIL WITH PATTERN SUGGESTIONS
    // ============================================================
    println!("📧 SECTION 2: Email Information\n");

    println!("Available email domains:");
    for domain in email_pattern.suggest("@") {
        println!("   {}", domain);
    }
    println!();

    let email = prompts::text(
        "Enter email address",
        None,
        Some("user@company.com"),
    )?;

    // Add to history
    email_history.add(email.clone());

    println!("✓ Email: {}\n", email);

    // Show email pattern suggestions
    if !email.contains('@') {
        if let Some(suggestion) = email_pattern.complete(&email) {
            println!("💡 Pattern suggestion: {}{}\n", email, suggestion);
        }
    }

    // ============================================================
    // SECTION 3: PASSWORD INPUT
    // ============================================================
    println!("🔒 SECTION 3: Security\n");

    let _password = prompts::password(
        "Enter password (minimum 8 characters)",
        false,
    )?;

    println!("✓ Password: ••••••••\n");

    let _confirm = prompts::password(
        "Confirm password",
        false,
    )?;

    println!("✓ Confirmed\n");

    // ============================================================
    // SECTION 4: LOCATION WITH FILTERED SELECTION
    // ============================================================
    println!("🌍 SECTION 4: Location\n");

    // Demonstrate filtering
    let countries_for_dialog = vec![
        "United States".to_string(),
        "Canada".to_string(),
        "Mexico".to_string(),
        "United Kingdom".to_string(),
        "Germany".to_string(),
        "France".to_string(),
        "Spain".to_string(),
        "Italy".to_string(),
        "Other".to_string(),
    ];

    println!("Available countries (filtered example):");
    let filtered = country_completer.filter("united");
    for country in &filtered {
        println!("   ✓ {}", country);
    }
    println!();

    let country = prompts::select(
        "Select your country",
        countries_for_dialog,
        None,
        false,
    )?;

    println!("✓ Country: {}\n", country);

    // ============================================================
    // SECTION 5: COMPANY INFORMATION
    // ============================================================
    println!("🏢 SECTION 5: Company Information\n");

    let company = prompts::text(
        "Company name (optional)",
        None,
        Some("Acme Corporation"),
    )?;

    println!("✓ Company: {}\n", company);

    // ============================================================
    // SECTION 6: WEBSITE URL WITH PATTERN
    // ============================================================
    println!("🔗 SECTION 6: Online Presence\n");

    println!("Available protocols for URL:");
    for protocol in url_pattern.suggest("") {
        println!("   {}", protocol);
    }
    println!();

    let website = prompts::text(
        "Company website",
        None,
        Some("https://"),
    )?;

    println!("✓ Website: {}\n", website);

    // ============================================================
    // SECTION 7: CONFIRMATION
    // ============================================================
    println!("✅ SECTION 7: Preferences\n");

    let subscribe = prompts::confirm(
        "Subscribe to our newsletter for updates?",
        Some(true),
        None,
    )?;

    println!("✓ Newsletter subscription: {}\n", if subscribe { "Yes" } else { "No" });

    // ============================================================
    // SUMMARY
    // ============================================================
    println!("╔════════════════════════════════════════════════════════════════╗");
    println!("║                    Registration Complete!                      ║");
    println!("╚════════════════════════════════════════════════════════════════╝\n");

    println!("📝 Summary of Registration:\n");
    println!("   Username:     {}", username);
    println!("   Email:        {}", email);
    println!("   Country:      {}", country);
    println!("   Company:      {}", if company.is_empty() { "(not provided)" } else { &company });
    println!("   Website:      {}", if website.is_empty() { "(not provided)" } else { &website });
    println!("   Newsletter:   {}\n", if subscribe { "✓ Subscribed" } else { "✗ Not subscribed" });

    // ============================================================
    // AUTOCOMPLETION INSIGHTS
    // ============================================================
    println!("💡 Autocompletion Insights:\n");

    println!("   📊 Username History ({}): ", username_history.get_history().len());
    for name in username_history.get_history() {
        println!("      - {}", name);
    }
    println!();

    println!("   📊 Email History ({}): ", email_history.get_history().len());
    for email_addr in email_history.get_history() {
        println!("      - {}", email_addr);
    }
    println!();

    println!("   💡 Pattern Completions:");
    println!("      - Email patterns: {}", email_pattern.suggest("@").len());
    println!("      - URL patterns: {}", url_pattern.suggest("").len());
    println!("      - Available countries: {}", countries.len());

    println!("\n✨ All three autocompletion strategies integrated successfully!");

    Ok(())
}
