//! Unified Content Grid Component
//!
//! Generic content grid that works with any content type dynamically,
//! using content type keys to distinguish between different content types.

use ::rustelo_core_lib::{
    // content::traits::*,
    create_content_kind_registry,
    fluent::load_content_index,
    i18n::create_content_provider, //  fluent::models::ContentIndex,
};
use leptos::prelude::*;

use crate::{
    content::card::UnifiedContentCard, content::pagination::PaginationControls,
    filter::unified::UnifiedCategoryFilter,
};

/// Unified Content Grid component that works with any content type
/// Uses content type keys to distinguish between different content types
#[component]
pub fn UnifiedContentGrid(
    content_type: String,
    language: String,
    #[prop(optional)] lang_content: Option<std::collections::HashMap<String, String>>,
    #[prop(default = true)] show_categories: bool,
    #[prop(default = false)] _use_filter: bool,
    #[prop(default = "".to_string())] category_filter: String,
    #[prop(default = 12)] limit: usize,
    #[prop(default = 1)] current_page: u32,
    #[prop(default = true)] enable_pagination: bool,
) -> AnyView {
    let content = create_content_provider(lang_content.clone());
    let show_cats = show_categories;

    // Pagination state - simple implementation for now
    let page = RwSignal::new(current_page);
    let page_size = RwSignal::new(0u32); // Will be set from config
    let set_page = page.write_only();
    let set_page_size = page_size.write_only();

    let content_config = {
        let registry = create_content_kind_registry();
        registry
            .kinds
            .get(&content_type)
            .cloned()
            .unwrap_or_else(|| {
                tracing::error!(
                    "❌ CONFIG_ERROR: Unknown content_type: '{}', available configs: {:?}, using \
                     default config - WASM FILESYSTEM ISSUE!",
                    content_type,
                    registry.kinds.keys().collect::<Vec<_>>()
                );
                rustelo_core_lib::ContentConfig::from_env()
            })
    };

    // Set pagination configuration from content config
    let config_page_size = 12; // Default page size
    let config_page_size_options = vec![6, 12, 24, 48]; // Default options
    let config_show_page_info = true; // Default to showing page info

    // Initialize page size from config
    if page_size.get_untracked() == 0 {
        set_page_size.set(config_page_size);
    }

    // Simple navigation function using custom navigation system
    let update_page_in_url = move |new_page: u32, _new_page_size: u32| {
        #[cfg(target_arch = "wasm32")]
        {
            if let Some(_set_path) = use_context::<WriteSignal<String>>() {
                // For now, just update the page state without URL changes
                // TODO: Implement URL query parameter support in custom navigation system
                tracing::debug!("Page changed to: {}", new_page);
                // Future: nav::anchor_navigate(set_path, &url_with_params);
            }
        }
        #[cfg(not(target_arch = "wasm32"))]
        {
            tracing::debug!("Page changed to: {} (SSR mode)", new_page);
        }
    };

    // Debug: Log the style_mode for this content type
    let css_classes = format!(
        "{} content-type-{} layout-{}",
        "default", // Default CSS style
        &content_type,
        "grid-layout" // Default layout class
    );
    // Use provided language directly
    let lang = language.clone();

    let get_css_mode = {
        move |item_count: usize, style_mode: &str| -> String {
            if style_mode == "grid" {
                if item_count == 1 {
                    String::from("grid grid-cols-1 gap-8 max-w-2xl mx-auto")
                } else if item_count == 2 {
                    String::from("grid md:grid-cols-2 gap-8")
                } else {
                    String::from("grid md:grid-cols-2 lg:grid-cols-2 gap-8")
                }
            } else {
                String::from("flex flex-col gap-8")
            }
        }
    };

    // WASM version with reactive loading
    #[cfg(target_arch = "wasm32")]
    {
        // Initialize with loaded content to match SSR initial state and prevent
        // hydration mismatch
        let initial_content = load_content_index(&content_type, &lang).unwrap_or_else(|e| {
            tracing::error!("Failed to load initial content index: {}", e);
            rustelo_core_lib::fluent::ContentIndex::default()
        });

        let content_index = RwSignal::new(Some(initial_content));

        let content_type_for_effect = content_type.clone();
        let lang_for_effect = lang.clone();
        let content_index_for_effect = content_index.clone();

        // Use Effect to reactively reload content when content_type or lang changes
        Effect::new(move |_| {
            let result = load_content_index(&content_type_for_effect, &lang_for_effect);
            content_index_for_effect.set(Some(result.unwrap_or_else(|e| {
                tracing::error!("Failed to reload content index: {}", e);
                rustelo_core_lib::fluent::ContentIndex::default()
            })));
        });

        view! {
            {move || content_index.with(|index_opt| {
                render_content_grid(
                    index_opt.as_ref(),
                    show_cats,
                    &category_filter,
                    &content_type,
                    &lang,
                    &css_classes,
                    &content_config,
                    get_css_mode,
                    page,
                    set_page,
                    page_size,
                    set_page_size,
                    enable_pagination,
                    config_page_size_options.clone(),
                    config_show_page_info,
                    update_page_in_url,
                    &content,
                    limit,
                )
            })}
        }
        .into_any()
    }

    // SSR version with direct loading
    #[cfg(not(target_arch = "wasm32"))]
    {
        let load_result = load_content_index(&content_type, &lang);
        let index_option = match load_result {
            Ok(index) => Some(index),
            Err(e) => {
                tracing::error!("Failed to load content index: {}", e);
                Some(rustelo_core_lib::fluent::ContentIndex::default())
            }
        };

        render_content_grid(
            index_option.as_ref(),
            show_cats,
            &category_filter,
            &content_type,
            &lang,
            &css_classes,
            &content_config,
            get_css_mode,
            page,
            set_page,
            page_size,
            set_page_size,
            enable_pagination,
            config_page_size_options,
            config_show_page_info,
            update_page_in_url,
            &content,
            limit,
        )
        .into_any()
    }
}

fn render_content_grid(
    index_opt: Option<&rustelo_core_lib::fluent::ContentIndex>,
    show_cats: bool,
    category_filter: &str,
    content_type: &str,
    lang: &str,
    css_classes: &str,
    content_config: &rustelo_core_lib::ContentConfig,
    get_css_mode: impl Fn(usize, &str) -> String,
    page: RwSignal<u32>,
    set_page: WriteSignal<u32>,
    page_size: RwSignal<u32>,
    set_page_size: WriteSignal<u32>,
    enable_pagination: bool,
    config_page_size_options: Vec<u32>,
    config_show_page_info: bool,
    update_page_in_url: impl Fn(u32, u32) + Clone + Send + Sync + 'static,
    content: &rustelo_core_lib::i18n::ContentProvider,
    limit: usize,
) -> impl IntoView {
    match index_opt {
        Some(index) => {
            let mut index = index.clone();

            // Debug logging
            #[cfg(target_arch = "wasm32")]
            {
                web_sys::console::log_1(
                    &format!(
                        "✅ CLIENT GRID: Loaded {} items for type='{}', lang='{}'",
                        index.items.len(),
                        content_type,
                        lang
                    )
                    .into(),
                );
            }

            // Filter for published items first
            index.items.retain(|item| item.published);

            // Now filter by category if specified (skip if empty or "all")
            #[cfg(target_arch = "wasm32")]
            {
                web_sys::console::log_1(
                    &format!("🔍 CLIENT GRID: Category filter: '{}'", category_filter).into(),
                );
            }

            if !category_filter.is_empty() && category_filter.to_lowercase() != "all" {
                #[cfg(target_arch = "wasm32")]
                {
                    let original_count = index.items.len();
                    web_sys::console::log_1(
                        &format!(
                            "🔍 CLIENT GRID: Applying category filter '{}' to {} items",
                            category_filter, original_count
                        )
                        .into(),
                    );
                }

                index.items.retain(|item| {
                    item.categories
                        .iter()
                        .any(|cat| cat.to_lowercase() == category_filter.to_lowercase())
                });

                #[cfg(target_arch = "wasm32")]
                {
                    web_sys::console::log_1(
                        &format!(
                            "🔍 CLIENT GRID: After category filter: {} items remaining",
                            index.items.len()
                        )
                        .into(),
                    );
                }
            } else {
                #[cfg(target_arch = "wasm32")]
                {
                    web_sys::console::log_1(
                        &format!(
                            "🔍 CLIENT GRID: No category filtering - showing all {} items",
                            index.items.len()
                        )
                        .into(),
                    );
                }
            }

            // Store total items before pagination for pagination controls
            let total_filtered_items = index.items.len() as u32;

            // Apply pagination if enabled
            let items_to_display = if enable_pagination {
                let current_page_num = page.get_untracked();
                let items_per_page = page_size.get_untracked() as usize;
                let start_idx = ((current_page_num - 1) * page_size.get_untracked()) as usize;
                let end_idx = std::cmp::min(start_idx + items_per_page, index.items.len());

                if start_idx < index.items.len() {
                    index.items.drain(start_idx..end_idx).collect()
                } else {
                    Vec::new()
                }
            } else {
                // Apply original limit if pagination is disabled
                index.items.truncate(limit);
                index.items
            };

            // Split items into featured and regular groups to avoid iterator consumption
            // issues
            let (featured_items, regular_items): (Vec<_>, Vec<_>) =
                items_to_display.into_iter().partition(|item| item.featured);

            let featured_count = featured_items.len();
            let regular_count = regular_items.len();
            let _item_count = featured_count + regular_count;

            // Check which sections we'll render to determine the logic flow
            let has_featured = !featured_items.is_empty();
            let has_regular = !regular_items.is_empty();

            view! {
                <div class="content-grid max-w-7xl mx-auto px-4">
                    {
                        // Debug logging for both server and client
                        tracing::debug!(
                            "GRID: Filter conditions - show_cats: {}, category_filter: '{}' (filter will load its own data)",
                            show_cats, category_filter
                        );

                        // Additional browser console logging
                        #[cfg(target_arch = "wasm32")]
                        {
                            web_sys::console::log_1(
                                &format!(
                                    "🔍 CLIENT GRID FILTER: show_cats={}, category_filter='{}' (filter will handle its own data loading)",
                                    show_cats, category_filter
                                ).into(),
                            );
                        }

                        // Render filter when show_cats is true - always show the filter regardless of current category
                        if show_cats {
                        view! {
                            <div class="category-filter mb-8">
                                <UnifiedCategoryFilter
                                    content_type=content_type.to_string()
                                    language=lang.to_string()
                                    _all_emoji="🏷️".to_string()
                                />
                            </div>
                        }.into_any()
                    } else {
                        #[cfg(target_arch = "wasm32")]
                        {
                            web_sys::console::log_1(
                                &format!(
                                    "❌ CLIENT GRID FILTER: NOT rendering filter - show_cats={}",
                                    show_cats
                                ).into(),
                            );
                        }
                        view! { <></> }.into_any()
                    }}

                    // Render content based on what we have
                    {if has_featured && has_regular {
                        // Layout with featured posts on the right and regular posts on the left
                        view! {
                            <div class="content-layout grid lg:grid-cols-3 gap-8">
                                // Regular items on the left (2/3 width)
                                <div class="lg:col-span-2">
                                    <div class={
                                        // 🔍 CRITICAL: Debug the exact values being passed to get_css_mode
                                        let style_mode_value = "grid"; // Default style mode
                                        format!("regular-grid {} items-stretch {}", css_classes,
                                            get_css_mode(regular_count, style_mode_value)
                                        )
                                    }>
                                        {regular_items.into_iter().map(|item| {
                                            view! {
                                                <UnifiedContentCard
                                                    content_item=item.clone()
                                                    content_type=content_type.to_string()
                                                    language=lang.to_string()
                                                    lang_content=std::collections::HashMap::new()
                                                    _content_config=content_config.clone()
                                                />
                                            }
                                        }).collect_view()}
                                    </div>
                                </div>

                                // Featured items on the right (1/3 width)
                                <div class="lg:col-span-1">
                                    <div class="featured-section">
                                        <h3 class="text-lg font-semibold mb-4 ds-text no-underline">
                                            {content.t_with_prefixes("featured", &[content_type, "content"], Some("Featured"))}
                                        </h3>
                                        <div class="space-y-4">
                                            {featured_items.into_iter().map(|item| {
                                                view! {
                                                    <UnifiedContentCard
                                                        content_item=item.clone()
                                                        content_type=content_type.to_string()
                                                        language=lang.to_string()
                                                        lang_content=std::collections::HashMap::new()
                                                        _content_config=content_config.clone()
                                                    />
                                                }
                                            }).collect_view()}
                                        </div>
                                    </div>
                                </div>
                            </div>
                        }.into_any()
                    } else if has_featured {
                        // Only featured items - display in grid
                        view! {
                            <div class="featured-grid">
                                <div class={
                                    let style_mode_value = "grid"; // Default style mode
                                    format!("featured-only {} {}", css_classes,
                                        get_css_mode(featured_count, style_mode_value)
                                    )
                                }>
                                    {featured_items.into_iter().map(|item| {
                                        view! {
                                            <UnifiedContentCard
                                                content_item=item.clone()
                                                content_type=content_type.to_string()
                                                language=lang.to_string()
                                                lang_content=std::collections::HashMap::new()
                                                _content_config=content_config.clone()
                                            />
                                        }
                                    }).collect_view()}
                                </div>
                            </div>
                        }.into_any()
                    } else if has_regular {
                        // Only regular items - display in grid
                        view! {
                            <div class="regular-grid">
                                <div class={
                                    let style_mode_value = "grid"; // Default style mode
                                    format!("regular-only {} {}", css_classes,
                                        get_css_mode(regular_count, style_mode_value)
                                    )
                                }>
                                    {regular_items.into_iter().map(|item| {
                                        view! {
                                            <UnifiedContentCard
                                                content_item=item.clone()
                                                content_type=content_type.to_string()
                                                language=lang.to_string()
                                                lang_content=std::collections::HashMap::new()
                                                _content_config=content_config.clone()
                                            />
                                        }
                                    }).collect_view()}
                                </div>
                            </div>
                        }.into_any()
                    } else {
                        view! {
                            <div class="regular-grid">
                                <div class={
                                    let style_mode_value = "grid"; // Default style mode
                                    format!("empty-only {} {}", css_classes,
                                        get_css_mode(0, style_mode_value)
                                    )
                                }>
                                    {vec![view! {
                                        <div class="empty-content">
                                            <p class="text-gray-500 text-center">"No content available"</p>
                                        </div>
                                    }].into_iter().collect_view()}
                                </div>
                            </div>
                        }.into_any()
                    }}

                    // Pagination controls
                    {if enable_pagination && total_filtered_items > 0 {
                        let total_pages = Memo::new(move |_| ((total_filtered_items + page_size.get() - 1) / page_size.get()).max(1));

                        // Pagination callbacks
                        let page_change_callback = {
                            let update_func = update_page_in_url.clone();
                            Callback::new(move |new_page: u32| {
                                set_page.set(new_page);
                                update_func(new_page, page_size.get_untracked());
                            })
                        };

                        let page_size_change_callback = {
                            let update_func = update_page_in_url.clone();
                            Callback::new(move |new_page_size: u32| {
                                set_page_size.set(new_page_size);
                                set_page.set(1); // Reset to first page when changing page size
                                update_func(1, new_page_size);
                            })
                        };

                        view! {
                            <PaginationControls
                                current_page=Signal::from(page)
                                total_pages=Signal::from(total_pages)
                                total_items=total_filtered_items
                                items_per_page=Signal::from(page_size)
                                content_type=content_type.to_string()
                                lang_content=std::collections::HashMap::new()
                                on_page_change=page_change_callback
                                on_page_size_change=page_size_change_callback
                                page_size_options=config_page_size_options
                                show_page_info=config_show_page_info
                            />
                        }.into_any()
                    } else {
                        view! { <></> }.into_any()
                    }}
                </div>
            }
            .into_any()
        }
        None => {
            // Loading state - content not yet loaded
            view! {
                <div class="content-grid">
                    <div class="animate-pulse">
                        <div class="h-4 bg-gray-200 rounded w-3/4 mb-4"></div>
                        <div class="h-4 bg-gray-200 rounded w-1/2 mb-6"></div>
                        <div class="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
                            {(0..6).map(|_| view! {
                                <div class="bg-gray-100 h-64 rounded-lg"></div>
                            }).collect_view()}
                        </div>
                    </div>
                </div>
            }
            .into_any()
        }
    }
}
