//! # Basic Pages Example
//!
//! Demonstrates configuration-driven page creation using TOML route configuration
//! instead of manual page component instantiation and routing.

use rustelo_pages::{create_app_from_config, PageConfig, run_example_server};
use rustelo_core_types::{RouteConfigToml, RoutesConfig};

/// Configuration-Driven Page Example
///
/// This example shows how pages are generated from TOML configuration
/// rather than manually creating page components and routing.
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("🎯 RUSTELO PAGES BASIC EXAMPLE");
    println!("==============================");
    println!();

    println!("This example demonstrates how pages are generated from TOML configuration");
    println!("instead of manually creating page components and routing.");
    println!();

    demonstrate_toml_page_config();
    println!();

    demonstrate_generated_pages();
    println!();

    demonstrate_page_extensions();

    Ok(())
}

/// Step 1: TOML Configuration → Page Generation
///
/// Shows how page components are defined in configuration files
fn demonstrate_toml_page_config() {
    println!("📋 STEP 1: TOML CONFIGURATION → PAGE GENERATION");
    println!("==============================================");
    println!();

    println!("📝 File: site/config/routes/en.toml");
    let page_config = r#"
[[routes]]
path = "/"
component = "Home"
title_key = "home-title"
description_key = "home-description"
language = "en"
enabled = true
page_type = "landing"

[[routes]]
path = "/about"
component = "About"
title_key = "about-title"
description_key = "about-description"
language = "en"
enabled = true
page_type = "content"
content_source = "about.md"


[[routes]]
path = "/contact"
component = "Contact"
title_key = "contact-title"
description_key = "contact-description"
language = "en"
enabled = true
page_type = "form"
form_config = "contact_form.toml"

[[routes]]
path = "/blog/{slug}"
component = "BlogPost"
title_key = "blog-post-title"
description_key = "blog-post-description"
language = "en"
enabled = true
page_type = "dynamic"
content_type = "blog"
"#;

    println!("{}", page_config);
    println!();

    println!("⚙️  Generated Page Features:");
    println!("   • HomePage (landing page from config)");
    println!("   • AboutPage (content page from about.md)");
    println!("   • ContactPage (form page with contact_form.toml)");
    println!("   • BlogPostPage (dynamic page for blog posts)");
    println!("   • Routing system (generated from paths)");
}

/// Step 2: Generated Page Components
///
/// Shows the page components that get generated automatically from TOML configuration
fn demonstrate_generated_pages() {
    println!("🏗️ STEP 2: GENERATED PAGE COMPONENTS");
    println!("===================================");
    println!();

    println!("📦 Generated Page Code (from routes TOML):");

    let generated_example = r#"
// Generated from your route configuration
#[component]
pub fn GeneratedApp() -> impl IntoView {
    // App structure generated from TOML routes
    view! {
        <AppProvider>
            <ThemeProvider>
                <I18nProvider>
                    // Generated routing based on TOML configuration
                    <ConfiguredRouter>
                        {generate_routes_from_config()}
                    </ConfiguredRouter>
                </I18nProvider>
            </ThemeProvider>
        </AppProvider>
    }
}

// Generated routing from TOML configuration
fn generate_routes_from_config() -> impl IntoView {
    view! {
        <Switch fallback=|| view! { <NotFoundPage /> }>
            // Generated from [[routes]] in TOML
            <Route path="/" view=GeneratedHomePage />
            <Route path="/about" view=GeneratedAboutPage />
            <Route path="/contact" view=GeneratedContactPage />
            <Route path="/blog/:slug" view=GeneratedBlogPostPage />
        </Switch>
    }
}

// Individual page components generated from configuration
#[component]
pub fn GeneratedHomePage() -> impl IntoView {
    let i18n = use_i18n();

    view! {
        <PageLayout page_type="landing">
            <PageHeader
                title=i18n.t("home-title")
                description=i18n.t("home-description")
            />
            <HomePageContent />
        </PageLayout>
    }
}

#[component]
pub fn GeneratedAboutPage() -> impl IntoView {
    let i18n = use_i18n();
    let content = use_content_from_markdown("about.md");

    view! {
        <PageLayout page_type="content">
            <PageHeader
                title=i18n.t("about-title")
                description=i18n.t("about-description")
            />
            <ContentRenderer content=content />
        </PageLayout>
    }
}


#[component]
pub fn GeneratedContactPage() -> impl IntoView {
    let i18n = use_i18n();
    let form_config = use_form_config("contact_form.toml");

    view! {
        <PageLayout page_type="form">
            <PageHeader
                title=i18n.t("contact-title")
                description=i18n.t("contact-description")
            />
            <DynamicForm config=form_config />
        </PageLayout>
    }
}
"#;

    println!("{}", generated_example);
    println!();

    println!("🎯 Usage Example:");
    let usage_example = r#"
// In your application main.rs
use rustelo_pages::create_app_from_config;

fn main() {
    // Pages generated automatically from TOML configuration
    let app = create_app_from_config("site/config/routes/en.toml")?;

    // Mount the generated application
    mount_to_body(app);
}

// Or run a development server with generated pages
use rustelo_pages::run_dev_server_with_config;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Start development server with pages from configuration
    run_dev_server_with_config("site/config/routes").await
}
"#;

    println!("{}", usage_example);
}

/// Step 3: Page Extensions (10% Custom Code)
///
/// Shows how to extend generated pages with custom functionality
fn demonstrate_page_extensions() {
    println!("🔧 STEP 3: PAGE EXTENSIONS (10% CUSTOM)");
    println!("======================================");
    println!();

    println!("For complex page requirements beyond TOML configuration:");
    println!();

    let extension_example = r#"
// Custom page extension for complex business logic
use rustelo_pages::{PageExtension, create_app_with_extensions};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Foundation provides 90% from TOML routes
    let base_app = create_app_from_config("site/config/routes/en.toml")?;

    // Add 10% custom page functionality
    let extended_app = base_app
        .extend_with_custom_pages(vec![
            CustomDashboardPage::new(),
            AdvancedAnalyticsPage::new(),
            RealtimeMonitoringPage::new(),
        ])
        .with_custom_routing(CustomRouting::new())
        .with_advanced_state_management(AdvancedStateManager::new());

    mount_to_body(extended_app);
    Ok(())
}

// Custom page that extends generated functionality
#[component]
pub fn CustomDashboardPage() -> impl IntoView {
    // Use generated base page component (90%)
    let base_layout = rustelo_pages::get_generated_page_layout("dashboard");

    // Add custom interactive features (10%)
    let (realtime_data, set_realtime_data) = create_signal(Vec::new());
    let (user_activity, set_user_activity) = create_signal(UserActivity::default());

    // Custom WebSocket connection for real-time updates
    create_effect(move |_| {
        spawn_local(async move {
            if let Ok(ws_stream) = connect_to_dashboard_stream().await {
                while let Some(update) = ws_stream.next().await {
                    match update {
                        DashboardUpdate::Data(data) => set_realtime_data.set(data),
                        DashboardUpdate::Activity(activity) => set_user_activity.set(activity),
                    }
                }
            }
        });
    });

    // Custom data processing that can't be expressed in TOML
    let processed_metrics = create_memo(move |_| {
        let data = realtime_data.get();
        let activity = user_activity.get();

        // Complex business logic for dashboard metrics
        compute_advanced_dashboard_metrics(&data, &activity)
    });

    view! {
        <div class="custom-dashboard-page">
            // Base page structure (90% from configuration)
            {base_layout}

            // Custom extensions (10% when configuration isn't sufficient)
            <RealtimeDataVisualization data=realtime_data />
            <AdvancedMetricsPanel metrics=processed_metrics />
            <InteractiveCharting />
            <CustomUserActivityTracker activity=user_activity />
        </div>
    }
}

// Custom page type that handles complex routing
#[derive(Debug, Clone)]
pub struct CustomDashboardPage {
    config: DashboardConfig,
}

impl PageExtension for CustomDashboardPage {
    fn route_pattern(&self) -> &str {
        "/dashboard/{section}/{subsection}"
    }

    fn component_name(&self) -> &str {
        "CustomDashboard"
    }

    fn render(&self, params: RouteParams) -> impl IntoView {
        let section = params.get("section").unwrap_or("overview");
        let subsection = params.get("subsection").unwrap_or("default");

        view! {
            <CustomDashboardPage section=section subsection=subsection />
        }
    }

    fn requires_auth(&self) -> bool {
        true
    }

    fn allowed_roles(&self) -> Vec<&str> {
        vec!["admin", "dashboard_viewer"]
    }
}

// Build-time extension for generating custom pages
#[cfg(feature = "build-extensions")]
pub struct CustomPageExtension;

impl PageBuildExtension for CustomPageExtension {
    fn name(&self) -> &str {
        "custom-dashboard-pages"
    }

    fn generate_page_code(&self, route_config: &RoutesConfig) -> Result<String, String> {
        let mut custom_code = String::new();

        // Generate custom pages based on route configuration
        for route in &route_config.routes {
            if route.page_type.as_deref() == Some("custom_dashboard") {
                custom_code.push_str(&format!(r#"
                    #[component]
                    pub fn {}() -> impl IntoView {{
                        view! {{
                            <CustomDashboardLayout route_path="{}">
                                <DashboardContent />
                                <RealtimeUpdates />
                                <AdvancedControls />
                            </CustomDashboardLayout>
                        }}
                    }}
                "#, route.component, route.path));
            }
        }

        Ok(custom_code)
    }

    fn dependencies(&self) -> Vec<String> {
        vec![
            "tokio-tungstenite".to_string(), // For WebSocket connections
            "serde_json".to_string(),        // For data processing
            "chrono".to_string(),            // For time-based features
        ]
    }
}

// Configuration validation example
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_page_configuration_validation() {
        let toml_config = r#"
            [[routes]]
            path = "/test"
            component = "TestPage"
            title_key = "test-title"
            language = "en"
            enabled = true
            page_type = "content"
        "#;

        let routes_config: RoutesConfig = toml::from_str(toml_config).unwrap();
        assert_eq!(routes_config.routes.len(), 1);

        let route = &routes_config.routes[0];
        assert_eq!(route.path, "/test");
        assert_eq!(route.component, "TestPage");
        assert_eq!(route.page_type.as_deref().unwrap(), "content");
    }

    #[test]
    fn test_generated_pages_creation() {
        let config = RoutesConfig {
            routes: vec![
                RouteConfigToml {
                    path: "/home".to_string(),
                    component: "Home".to_string(),
                    title_key: "home-title".to_string(),
                    language: "en".to_string(),
                    enabled: true,
                    ..Default::default()
                }
            ],
            settings: None,
        };

        // Test that page generation works with configuration
        let generated_pages = generate_pages_from_config(&config);
        assert_eq!(generated_pages.len(), 1);
        assert_eq!(generated_pages[0].route, "/home");
        assert_eq!(generated_pages[0].component_name, "Home");
    }
}
"#;

    println!("{}", extension_example);

    println!();
    println!("💡 Key Page Generation Principles:");
    println!("   • Pages defined in TOML route configuration (90%)");
    println!("   • Automatic generation of page components and routing");
    println!("   • Content integration from markdown files");
    println!("   • Form pages generated from form configuration");
    println!("   • Dynamic pages for parametric routes");
    println!("   • Custom extensions for complex page requirements (10%)");
    println!();

    println!("⚖️ When to Use Page Extensions:");
    println!("   ✅ Complex interactive dashboards");
    println!("   ✅ Real-time data visualization pages");
    println!("   ✅ Advanced form handling and validation");
    println!("   ✅ Custom authentication flows");
    println!("   ✅ Third-party integration pages");
    println!();

    println!("❌ When NOT to Use Extensions:");
    println!("   ❌ Basic content pages (use TOML + markdown)");
    println!("   ❌ Simple listing pages (use content_type configuration)");
    println!("   ❌ Standard forms (use form_config.toml)");
    println!("   ❌ Static pages (use page_type = \"content\")");
    println!("   ❌ Basic routing (use TOML route configuration)");
}

// Supporting types and mock implementations for the example

#[derive(Clone, Debug, Default)]
struct PageConfig {
    routes_file: String,
    theme_config: String,
    i18n_config: String,
}

#[derive(Clone, Debug, Default)]
struct UserActivity {
    page_views: u32,
    time_on_page: u64,
    interactions: u32,
}

#[derive(Clone, Debug)]
enum DashboardUpdate {
    Data(Vec<DataPoint>),
    Activity(UserActivity),
}

#[derive(Clone, Debug)]
struct DataPoint {
    timestamp: u64,
    value: f64,
    category: String,
}

#[derive(Clone, Debug)]
struct DashboardConfig {
    realtime_enabled: bool,
    update_interval: u64,
    data_sources: Vec<String>,
}

#[derive(Clone, Debug)]
struct RouteParams {
    params: std::collections::HashMap<String, String>,
}

impl RouteParams {
    fn get(&self, key: &str) -> Option<&str> {
        self.params.get(key).map(|s| s.as_str())
    }
}

#[derive(Clone, Debug)]
struct GeneratedPage {
    route: String,
    component_name: String,
    page_type: String,
}

// Mock implementations
async fn connect_to_dashboard_stream() -> Result<DashboardStream, String> { Ok(DashboardStream) }
fn compute_advanced_dashboard_metrics(_data: &[DataPoint], _activity: &UserActivity) -> Vec<Metric> { vec![] }
fn generate_pages_from_config(_config: &RoutesConfig) -> Vec<GeneratedPage> { vec![] }

struct DashboardStream;
impl DashboardStream {
    async fn next(&mut self) -> Option<DashboardUpdate> { None }
}

struct Metric;

// Mock page extension trait
trait PageExtension {
    fn route_pattern(&self) -> &str;
    fn component_name(&self) -> &str;
    fn render(&self, params: RouteParams) -> impl IntoView;
    fn requires_auth(&self) -> bool { false }
    fn allowed_roles(&self) -> Vec<&str> { vec![] }
}

trait PageBuildExtension {
    fn name(&self) -> &str;
    fn generate_page_code(&self, route_config: &RoutesConfig) -> Result<String, String>;
    fn dependencies(&self) -> Vec<String> { vec![] }
}

// Mock extension types
struct CustomDashboardPage;
struct AdvancedAnalyticsPage;
struct RealtimeMonitoringPage;
struct CustomRouting;
struct AdvancedStateManager;

impl CustomDashboardPage {
    fn new() -> Self { Self }
}

impl AdvancedAnalyticsPage {
    fn new() -> Self { Self }
}

impl RealtimeMonitoringPage {
    fn new() -> Self { Self }
}

impl CustomRouting {
    fn new() -> Self { Self }
}

impl AdvancedStateManager {
    fn new() -> Self { Self }
}