//! # Blog System Example
//!
//! Comprehensive demonstration of using pages foundation to build
//! a complete blog system with categories, tags, and content management.

use std::collections::HashMap;

use leptos::*;
use leptos_router::*;
use rustelo_components_leptos::{
    content::{SimpleContentGrid, UnifiedContentCard},
    filter::{FilterItem, UnifiedCategoryFilter},
    navigation::{BrandHeader, Footer, NavMenu},
    ui::SpaLink,
};
use rustelo_pages::{
    content::{ContentCategoryPage, ContentIndexPage, UnifiedContentIndexPage},
    NotFoundPage, PostViewerPage,
};
use serde::{Deserialize, Serialize};

/// Complete blog system built with pages foundation
#[component]
pub fn BlogSystem() -> impl IntoView {
    // Blog configuration
    let blog_config = BlogConfig::default();

    view! {
        <Router>
            <div class="min-h-screen bg-gray-50">
                <BlogHeader />

                <main class="container mx-auto px-4 py-8">
                    <Routes>
                        // Blog home - all posts
                        <Route path="/" view=move || {
                            view! {
                                <UnifiedContentIndexPage
                                    content_type="blog"
                                    title="Latest Blog Posts"
                                    description="Insights, tutorials, and updates from our team"
                                    layout="grid"
                                    per_page=10
                                    show_pagination=true
                                    show_search=true
                                    show_categories=true
                                />
                            }
                        } />

                        // Category pages
                        <Route path="/category/:category" view=BlogCategoryPage />

                        // Tag pages
                        <Route path="/tag/:tag" view=BlogTagPage />

                        // Individual blog posts
                        <Route path="/post/:slug" view=BlogPostPage />

                        // Archive pages
                        <Route path="/archive" view=BlogArchivePage />
                        <Route path="/archive/:year" view=BlogYearArchive />
                        <Route path="/archive/:year/:month" view=BlogMonthArchive />

                        // RSS and feeds
                        <Route path="/rss" view=BlogRSSFeed />
                        <Route path="/sitemap.xml" view=BlogSitemap />

                        // 404 page
                        <Route path="/*any" view=|| view! {
                            <NotFoundPage
                                title="Blog Post Not Found"
                                message="The blog post you're looking for doesn't exist."
                                home_url="/"
                            />
                        } />
                    </Routes>
                </main>

                <BlogFooter />
            </div>
        </Router>
    }
}

/// Blog header with navigation
#[component]
fn BlogHeader() -> impl IntoView {
    view! {
        <BrandHeader
            brand_name="Tech Blog"
            logo_url="/blog-logo.svg"
            class="bg-white shadow-sm border-b"
        >
            <NavMenu orientation="horizontal" class="space-x-6">
                <SpaLink
                    href="/"
                    class="px-3 py-2 text-gray-700 hover:text-blue-600 font-medium"
                    active_class="text-blue-600 border-b-2 border-blue-600"
                >
                    "Latest"
                </SpaLink>

                <SpaLink
                    href="/category/tutorials"
                    class="px-3 py-2 text-gray-700 hover:text-blue-600 font-medium"
                    active_class="text-blue-600 border-b-2 border-blue-600"
                >
                    "Tutorials"
                </SpaLink>

                <SpaLink
                    href="/category/news"
                    class="px-3 py-2 text-gray-700 hover:text-blue-600 font-medium"
                    active_class="text-blue-600 border-b-2 border-blue-600"
                >
                    "News"
                </SpaLink>

                <SpaLink
                    href="/category/reviews"
                    class="px-3 py-2 text-gray-700 hover:text-blue-600 font-medium"
                    active_class="text-blue-600 border-b-2 border-blue-600"
                >
                    "Reviews"
                </SpaLink>

                <SpaLink
                    href="/archive"
                    class="px-3 py-2 text-gray-700 hover:text-blue-600 font-medium"
                    active_class="text-blue-600 border-b-2 border-blue-600"
                >
                    "Archive"
                </SpaLink>
            </NavMenu>

            // Search and subscribe
            <div class="flex items-center space-x-4">
                <BlogSearchBox />
                <button class="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors">
                    "Subscribe"
                </button>
            </div>
        </BrandHeader>
    }
}

/// Blog search component
#[component]
fn BlogSearchBox() -> impl IntoView {
    let (search_query, set_search_query) = create_signal(String::new());
    let (search_results, set_search_results) = create_signal(Vec::new());
    let (show_results, set_show_results) = create_signal(false);

    let perform_search = move |query: String| {
        if query.len() >= 2 {
            spawn_local(async move {
                let results = search_blog_posts(&query).await;
                set_search_results.set(results);
                set_show_results.set(true);
            });
        } else {
            set_show_results.set(false);
        }
    };

    view! {
        <div class="relative">
            <input
                type="text"
                placeholder="Search posts..."
                class="w-64 px-3 py-2 border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                prop:value=search_query
                on:input=move |ev| {
                    let query = event_target_value(&ev);
                    set_search_query.set(query.clone());
                    perform_search(query);
                }
            />

            // Search results dropdown
            <Show when=move || show_results.get()>
                <div class="absolute top-full mt-1 w-full bg-white border border-gray-300 rounded-md shadow-lg z-10">
                    <For
                        each=move || search_results.get()
                        key=|post| post.slug.clone()
                        children=move |post| {
                            view! {
                                <SpaLink
                                    href=format!("/post/{}", post.slug)
                                    class="block px-4 py-2 hover:bg-gray-100 border-b border-gray-100 last:border-b-0"
                                    on:click=move |_| set_show_results.set(false)
                                >
                                    <div class="font-medium text-gray-900">{post.title.clone()}</div>
                                    <div class="text-sm text-gray-600 truncate">{post.excerpt.clone()}</div>
                                </SpaLink>
                            }
                        }
                    />

                    <Show when=move || search_results.get().is_empty()>
                        <div class="px-4 py-2 text-gray-500 text-center">
                            "No posts found"
                        </div>
                    </Show>
                </div>
            </Show>
        </div>
    }
}

/// Blog category page
#[component]
fn BlogCategoryPage() -> impl IntoView {
    let params = use_params_map();
    let category =
        move || params.with(|params| params.get("category").cloned().unwrap_or_default());

    view! {
        <div>
            // Category header with description
            <BlogCategoryHeader category=category />

            // Category content using foundation component
            <ContentCategoryPage
                content_type="blog"
                category=category
                layout="grid"
                per_page=12
                show_pagination=true
            />

            // Related categories sidebar
            <BlogCategorySidebar current_category=category />
        </div>
    }
}

/// Category header component
#[component]
fn BlogCategoryHeader(category: impl Fn() -> String + 'static) -> impl IntoView {
    let category_info = create_memo(move |_| get_category_info(&category()));

    view! {
        <div class="bg-blue-600 text-white py-12 mb-8">
            <div class="container mx-auto px-4">
                {move || {
                    let info = category_info.get();
                    view! {
                        <div class="max-w-3xl">
                            <h1 class="text-4xl font-bold mb-4">{info.title}</h1>
                            <p class="text-xl text-blue-100 mb-4">{info.description}</p>
                            <div class="flex items-center space-x-4 text-blue-200">
                                <span>{format!("{} posts", info.post_count)}</span>
                                <span>"•"</span>
                                <span>{format!("Updated {}", info.last_updated)}</span>
                            </div>
                        </div>
                    }
                }}
            </div>
        </div>
    }
}

/// Individual blog post page
#[component]
fn BlogPostPage() -> impl IntoView {
    let params = use_params_map();
    let slug = move || params.with(|params| params.get("slug").cloned().unwrap_or_default());

    view! {
        <div class="max-w-4xl mx-auto">
            // Use foundation PostViewerPage with blog-specific configuration
            <PostViewerPage
                content_type="blog"
                slug=slug
                show_author=true
                show_date=true
                show_tags=true
                show_related_posts=true
                enable_comments=true
                enable_social_sharing=true
            />

            // Blog-specific components
            <BlogPostSidebar slug=slug />
            <BlogPostNavigation slug=slug />
            <BlogPostComments slug=slug />
        </div>
    }
}

/// Blog post sidebar
#[component]
fn BlogPostSidebar(slug: impl Fn() -> String + 'static) -> impl IntoView {
    let (post_data, set_post_data) = create_signal(None::<BlogPost>);

    create_effect(move |_| {
        let current_slug = slug();
        spawn_local(async move {
            let post = load_blog_post(&current_slug).await;
            set_post_data.set(post.ok());
        });
    });

    view! {
        <aside class="lg:w-1/3 lg:pl-8 mt-12 lg:mt-0">
            // Author info
            {move || {
                post_data.get().map(|post| view! {
                    <UnifiedContentCard title="About the Author" class="mb-6">
                        <div class="flex items-center space-x-3 mb-3">
                            <img
                                src=post.author.avatar_url.clone()
                                alt=post.author.name.clone()
                                class="w-12 h-12 rounded-full"
                            />
                            <div>
                                <h4 class="font-semibold">{post.author.name.clone()}</h4>
                                <p class="text-sm text-gray-600">{post.author.title.clone()}</p>
                            </div>
                        </div>
                        <p class="text-sm text-gray-700">{post.author.bio.clone()}</p>
                        <div class="flex space-x-2 mt-3">
                            <SpaLink href=post.author.twitter_url.clone() class="text-blue-500 hover:text-blue-700">
                                "Twitter"
                            </SpaLink>
                            <SpaLink href=post.author.github_url.clone() class="text-gray-700 hover:text-gray-900">
                                "GitHub"
                            </SpaLink>
                        </div>
                    </UnifiedContentCard>
                })
            }}

            // Related posts
            <UnifiedContentCard title="Related Posts" class="mb-6">
                <BlogRelatedPosts slug=slug />
            </UnifiedContentCard>

            // Popular tags
            <UnifiedContentCard title="Popular Tags">
                <BlogPopularTags />
            </UnifiedContentCard>
        </aside>
    }
}

/// Related posts component
#[component]
fn BlogRelatedPosts(slug: impl Fn() -> String + 'static) -> impl IntoView {
    let (related_posts, set_related_posts) = create_signal(Vec::<BlogPost>::new());

    create_effect(move |_| {
        let current_slug = slug();
        spawn_local(async move {
            let posts = load_related_posts(&current_slug, 5).await;
            set_related_posts.set(posts.unwrap_or_default());
        });
    });

    view! {
        <div class="space-y-3">
            <For
                each=move || related_posts.get()
                key=|post| post.slug.clone()
                children=move |post| {
                    view! {
                        <div class="border-b border-gray-200 pb-3 last:border-b-0 last:pb-0">
                            <SpaLink
                                href=format!("/post/{}", post.slug)
                                class="block hover:text-blue-600 transition-colors"
                            >
                                <h5 class="font-medium text-sm mb-1">{post.title}</h5>
                                <p class="text-xs text-gray-600">{post.published_date}</p>
                            </SpaLink>
                        </div>
                    }
                }
            />
        </div>
    }
}

/// Blog archive page
#[component]
fn BlogArchivePage() -> impl IntoView {
    let (archive_data, set_archive_data) = create_signal(HashMap::<String, Vec<BlogPost>>::new());

    create_effect(move |_| {
        spawn_local(async move {
            let data = load_blog_archive().await;
            set_archive_data.set(data.unwrap_or_default());
        });
    });

    view! {
        <div>
            <div class="text-center mb-12">
                <h1 class="text-4xl font-bold text-gray-900 mb-4">"Blog Archive"</h1>
                <p class="text-xl text-gray-600">"Browse all our blog posts organized by date"</p>
            </div>

            <div class="space-y-8">
                <For
                    each=move || {
                        let mut years: Vec<_> = archive_data.get().keys().cloned().collect();
                        years.sort_by(|a, b| b.cmp(a)); // Reverse chronological order
                        years
                    }
                    key=|year| year.clone()
                    children=move |year| {
                        let posts = archive_data.get().get(&year).cloned().unwrap_or_default();
                        view! {
                            <div class="border border-gray-200 rounded-lg p-6">
                                <h2 class="text-2xl font-bold text-gray-900 mb-4">{year.clone()}</h2>
                                <SimpleContentGrid columns=1 gap="1rem" class="space-y-4">
                                    <For
                                        each=move || posts.clone()
                                        key=|post| post.slug.clone()
                                        children=move |post| {
                                            view! {
                                                <div class="flex items-start justify-between py-2 border-b border-gray-100">
                                                    <div class="flex-1">
                                                        <SpaLink
                                                            href=format!("/post/{}", post.slug)
                                                            class="text-lg font-medium text-gray-900 hover:text-blue-600"
                                                        >
                                                            {post.title}
                                                        </SpaLink>
                                                        <p class="text-gray-600 text-sm mt-1">{post.excerpt}</p>
                                                        <div class="flex items-center space-x-4 mt-2 text-xs text-gray-500">
                                                            <span>{post.published_date}</span>
                                                            <span>"•"</span>
                                                            <span>{post.author.name}</span>
                                                            <span>"•"</span>
                                                            <span>{post.category}</span>
                                                        </div>
                                                    </div>
                                                    <div class="ml-4 text-right">
                                                        <div class="flex flex-wrap gap-1">
                                                            {post.tags.into_iter().take(2).map(|tag| view! {
                                                                <span class="px-2 py-1 bg-gray-100 text-gray-700 text-xs rounded">
                                                                    {tag}
                                                                </span>
                                                            }).collect::<Vec<_>>()}
                                                        </div>
                                                    </div>
                                                </div>
                                            }
                                        }
                                    />
                                </SimpleContentGrid>
                            </div>
                        }
                    }
                />
            </div>
        </div>
    }
}

/// Blog footer
#[component]
fn BlogFooter() -> impl IntoView {
    view! {
        <Footer
            copyright="© 2024 Tech Blog"
            class="bg-gray-900 text-white"
        >
            <div class="grid md:grid-cols-4 gap-8">
                // Blog sections
                <div>
                    <h4 class="font-semibold mb-4">"Categories"</h4>
                    <div class="space-y-2 text-sm">
                        <SpaLink href="/category/tutorials" class="block text-gray-300 hover:text-white">
                            "Tutorials"
                        </SpaLink>
                        <SpaLink href="/category/news" class="block text-gray-300 hover:text-white">
                            "Tech News"
                        </SpaLink>
                        <SpaLink href="/category/reviews" class="block text-gray-300 hover:text-white">
                            "Product Reviews"
                        </SpaLink>
                        <SpaLink href="/category/guides" class="block text-gray-300 hover:text-white">
                            "How-to Guides"
                        </SpaLink>
                    </div>
                </div>

                // Popular posts
                <div>
                    <h4 class="font-semibold mb-4">"Popular Posts"</h4>
                    <div class="space-y-2 text-sm">
                        <SpaLink href="/post/getting-started-rust" class="block text-gray-300 hover:text-white">
                            "Getting Started with Rust"
                        </SpaLink>
                        <SpaLink href="/post/leptos-guide" class="block text-gray-300 hover:text-white">
                            "Complete Leptos Guide"
                        </SpaLink>
                        <SpaLink href="/post/wasm-performance" class="block text-gray-300 hover:text-white">
                            "WebAssembly Performance Tips"
                        </SpaLink>
                    </div>
                </div>

                // Subscribe
                <div>
                    <h4 class="font-semibold mb-4">"Subscribe"</h4>
                    <p class="text-sm text-gray-300 mb-4">"Get the latest posts delivered to your inbox"</p>
                    <div class="flex">
                        <input
                            type="email"
                            placeholder="your@email.com"
                            class="flex-1 px-3 py-2 text-gray-900 rounded-l-md"
                        />
                        <button class="bg-blue-600 text-white px-4 py-2 rounded-r-md hover:bg-blue-700">
                            "Subscribe"
                        </button>
                    </div>
                </div>

                // Social links
                <div>
                    <h4 class="font-semibold mb-4">"Follow Us"</h4>
                    <div class="flex space-x-4">
                        <a href="#" class="text-gray-300 hover:text-white">"Twitter"</a>
                        <a href="#" class="text-gray-300 hover:text-white">"GitHub"</a>
                        <a href="/rss" class="text-gray-300 hover:text-white">"RSS"</a>
                    </div>
                </div>
            </div>
        </Footer>
    }
}

// Data structures and helper functions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BlogPost {
    pub slug: String,
    pub title: String,
    pub excerpt: String,
    pub content: String,
    pub published_date: String,
    pub updated_date: Option<String>,
    pub author: Author,
    pub category: String,
    pub tags: Vec<String>,
    pub featured_image: Option<String>,
    pub reading_time: u32,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Author {
    pub name: String,
    pub email: String,
    pub bio: String,
    pub title: String,
    pub avatar_url: String,
    pub twitter_url: String,
    pub github_url: String,
}

#[derive(Debug, Clone)]
pub struct CategoryInfo {
    pub title: String,
    pub description: String,
    pub post_count: u32,
    pub last_updated: String,
}

#[derive(Debug, Clone)]
pub struct BlogConfig {
    pub site_name: String,
    pub site_description: String,
    pub posts_per_page: usize,
    pub show_excerpts: bool,
    pub enable_comments: bool,
    pub enable_search: bool,
}

impl Default for BlogConfig {
    fn default() -> Self {
        Self {
            site_name: "Tech Blog".to_string(),
            site_description: "Insights and tutorials on modern web development".to_string(),
            posts_per_page: 10,
            show_excerpts: true,
            enable_comments: true,
            enable_search: true,
        }
    }
}

// Mock data loading functions (replace with real implementations)
async fn search_blog_posts(query: &str) -> Vec<BlogPost> {
    // Simulate search API call
    vec![] // Replace with actual search implementation
}

async fn load_blog_post(slug: &str) -> Result<BlogPost, BlogError> {
    // Simulate post loading
    Ok(BlogPost {
        slug: slug.to_string(),
        title: "Sample Post".to_string(),
        excerpt: "This is a sample post excerpt".to_string(),
        content: "Full post content...".to_string(),
        published_date: "2024-01-01".to_string(),
        updated_date: None,
        author: Author {
            name: "John Doe".to_string(),
            email: "john@example.com".to_string(),
            bio: "Software developer and blogger".to_string(),
            title: "Senior Developer".to_string(),
            avatar_url: "/avatars/john.jpg".to_string(),
            twitter_url: "https://twitter.com/johndoe".to_string(),
            github_url: "https://github.com/johndoe".to_string(),
        },
        category: "tutorials".to_string(),
        tags: vec!["rust".to_string(), "leptos".to_string()],
        featured_image: Some("/images/post-featured.jpg".to_string()),
        reading_time: 5,
    })
}

async fn load_related_posts(slug: &str, limit: usize) -> Result<Vec<BlogPost>, BlogError> {
    // Simulate related posts loading
    Ok(vec![])
}

async fn load_blog_archive() -> Result<HashMap<String, Vec<BlogPost>>, BlogError> {
    // Simulate archive loading
    Ok(HashMap::new())
}

fn get_category_info(category: &str) -> CategoryInfo {
    // Return category information
    CategoryInfo {
        title: format!("{} Posts", category.to_uppercase()),
        description: format!("All posts in the {} category", category),
        post_count: 42,
        last_updated: "January 2024".to_string(),
    }
}

#[derive(Debug)]
pub enum BlogError {
    NotFound,
    LoadFailed(String),
}

// This comprehensive blog system demonstrates:
//
// ✅ **Complete Blog Architecture**
// - Multi-page blog with routing and navigation
// - Category and tag organization
// - Archive functionality
// - Search capabilities
//
// ✅ **Foundation Integration**
// - Uses ContentIndexPage for listing pages
// - PostViewerPage for individual posts
// - UnifiedContentCard for flexible content display
// - Seamless integration with navigation components
//
// ✅ **Rich Content Features**
// - Author profiles and social links
// - Related posts and recommendations
// - Popular tags and categories
// - Archive organized by year/month
//
// ✅ **User Experience**
// - Search functionality with live results
// - Responsive design for all devices
// - Fast SPA navigation
// - Loading states and error handling
//
// ✅ **SEO and Performance**
// - RSS feeds and sitemaps
// - Social sharing integration
// - Optimized content loading
// - Professional URL structure
//
// ✅ **Extensibility**
// - Configurable blog settings
// - Custom component integration
// - Easy content source switching
// - Plugin-friendly architecture
//
// To implement this blog system:
//
// 1. **Set up the routing structure**
// 2. **Configure content sources** (markdown files, database, API)
// 3. **Customize styling** to match your brand
// 4. **Add real data loading** functions
// 5. **Implement search** and filtering
// 6. **Add comment system** integration
// 7. **Set up RSS feeds** and sitemaps
//
// The foundation provides all the building blocks,
// you just need to connect your content and styling!
