//! Content Management UI Components
//!
//! Provides Leptos components for managing content through the REST API,
//! including content listing, creation, editing, and publishing controls.

use std::collections::HashMap;

use ::rustelo_core_lib::content::ContentItemManager;
use ::rustelo_core_lib::get_all_content_types;
use ::rustelo_core_lib::i18n::discovery;
use ::rustelo_core_lib::i18n::helpers::{build_page_content_patterns, UnifiedLocalizationHelper};
use leptos::prelude::*;

// Using unified content types from shared crate

/// Content management dashboard component - now fully language-agnostic and
/// configuration-driven
///
/// This component follows the project's best practices:
/// - Language agnostic: accepts language parameter and uses i18n
/// - Configuration-driven: discovers content types from content-kinds.toml
/// - No hardcoded strings: all text from Fluent i18n files
#[component]
pub fn ContentManager(#[prop(optional)] language: Option<String>) -> impl IntoView {
    // Use language-agnostic discovery system
    let current_language =
        language.unwrap_or_else(|| discovery::get_default_language().to_string());

    // Create i18n helper for this language
    let i18n = UnifiedLocalizationHelper::new(current_language.clone());

    // Load all content management i18n keys dynamically (zero maintenance!)
    let i18n_content = build_page_content_patterns(
        &i18n,
        &["content-manager-", "admin-", "content-", "common-"],
    );

    // Get available content types from configuration instead of hardcoding
    let available_content_types: Vec<String> = get_all_content_types()
        .iter()
        .map(|s| s.to_string())
        .collect();

    // Get available languages from configuration instead of hardcoding
    let available_languages: Vec<String> = discovery::discover_available_languages().clone();
    // Generate configuration-driven mock data based on available content types
    let mock_content = generate_mock_content_from_config(
        &available_content_types,
        &current_language,
        &i18n_content,
    );

    // Clone i18n_content for use in closures
    let i18n_for_table = i18n_content.clone();
    let i18n_for_note = i18n_content.clone();

    view! {
        <div class="content-manager p-6 max-w-7xl mx-auto">
            <div class="flex justify-between items-center mb-6">
                <h1 class="text-3xl font-bold text-gray-900">
                    {i18n_content.get("content-manager-title")
                        .cloned()
                        .unwrap_or_else(|| "Content Management".to_string())}
                </h1>
                <button class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg flex items-center gap-2">
                    <span class="text-lg">"+"</span>
                    {i18n_content.get("content-manager-new-content")
                        .cloned()
                        .unwrap_or_else(|| "New Content".to_string())}
                </button>
            </div>

            // Filters
            <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-4 mb-6">
                <div class="flex flex-wrap gap-4 items-center">
                    <div class="flex items-center gap-2">
                        <label for="filter-type" class="text-sm font-medium text-gray-700">
                            {i18n_content.get("content-manager-filter-type")
                                .cloned()
                                .unwrap_or_else(|| "Content Type:".to_string())}
                        </label>
                        <select id="filter-type" class="border border-gray-300 rounded-md px-3 py-1 text-sm">
                            <option value="all">
                                {i18n_content.get("content-manager-all-types")
                                    .cloned()
                                    .unwrap_or_else(|| "All Types".to_string())}
                            </option>
                            // Configuration-driven content type options
                            {
                                available_content_types.into_iter().map(|content_type| {
                                    let display_name = i18n_content.get(&format!("content-kind-{}", content_type))
                                        .cloned()
                                        .unwrap_or_else(|| content_type.clone());
                                    view! {
                                        <option value={content_type.clone()}>{display_name}</option>
                                    }
                                }).collect::<Vec<_>>()
                            }
                        </select>
                    </div>

                    <div class="flex items-center gap-2">
                        <label for="filter-language" class="text-sm font-medium text-gray-700">
                            {i18n_content.get("content-manager-filter-language")
                                .cloned()
                                .unwrap_or_else(|| "Language:".to_string())}
                        </label>
                        <select id="filter-language" class="border border-gray-300 rounded-md px-3 py-1 text-sm">
                            <option value="all">
                                {i18n_content.get("content-manager-all-languages")
                                    .cloned()
                                    .unwrap_or_else(|| "All Languages".to_string())}
                            </option>
                            // Configuration-driven language options
                            {
                                available_languages.into_iter().map(|lang_code| {
                                    let display_name = i18n_content.get(&format!("language-{}", lang_code))
                                        .cloned()
                                        .unwrap_or_else(|| lang_code.clone());
                                    view! {
                                        <option value={lang_code.clone()}>{display_name}</option>
                                    }
                                }).collect::<Vec<_>>()
                            }
                        </select>
                    </div>

                    <button class="bg-gray-600 hover:bg-gray-700 text-white px-3 py-1 rounded-md text-sm">
                        {i18n_content.get("content-manager-refresh")
                            .cloned()
                            .unwrap_or_else(|| "Refresh".to_string())}
                    </button>
                </div>
            </div>

            // Content List
            <div class="bg-white rounded-lg shadow-sm border border-gray-200">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="text-left p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-title")
                                        .cloned()
                                        .unwrap_or_else(|| "Title".to_string())}
                                </th>
                                <th class="text-left p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-type")
                                        .cloned()
                                        .unwrap_or_else(|| "Type".to_string())}
                                </th>
                                <th class="text-left p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-language")
                                        .cloned()
                                        .unwrap_or_else(|| "Language".to_string())}
                                </th>
                                <th class="text-left p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-status")
                                        .cloned()
                                        .unwrap_or_else(|| "Status".to_string())}
                                </th>
                                <th class="text-left p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-updated")
                                        .cloned()
                                        .unwrap_or_else(|| "Updated".to_string())}
                                </th>
                                <th class="text-center p-4 font-semibold text-gray-900">
                                    {i18n_content.get("content-manager-table-actions")
                                        .cloned()
                                        .unwrap_or_else(|| "Actions".to_string())}
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            <For
                                each=move || mock_content.clone()
                                key=|content| content.id.clone()
                                let:content
                            >
                                <ContentRow content=content i18n_content=i18n_for_table.clone() />
                            </For>
                        </tbody>
                    </table>
                </div>
            </div>

            // Status message
            <div class="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                <p class="text-blue-800 text-sm">
                    <strong>
                        {i18n_for_note.get("content-manager-note-label")
                            .cloned()
                            .unwrap_or_else(|| "Note:".to_string())}
                    </strong>
                    {" "}
                    {i18n_for_note.get("content-manager-note-text")
                        .cloned()
                        .unwrap_or_else(|| "This is a mockup of the content management interface. Full functionality with API integration will be implemented in future updates.".to_string())}
                </p>
            </div>
        </div>
    }
}

/// Content row component - now i18n-aware
#[component]
fn ContentRow(content: ContentItemManager, i18n_content: HashMap<String, String>) -> impl IntoView {
    view! {
        <tr class="border-b border-gray-200 hover:bg-gray-50">
            <td class="p-4">
                <div class="font-medium text-gray-900">{content.title.clone()}</div>
                <div class="text-sm text-gray-500">{content.slug.clone()}</div>
            </td>
            <td class="p-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                    {content.content_type.clone()}
                </span>
            </td>
            <td class="p-4">
                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                    {content.language.clone()}
                </span>
            </td>
            <td class="p-4">
                <span class={format!(
                    "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium {}",
                    if content.published {
                        "bg-green-100 text-green-800"
                    } else {
                        "bg-yellow-100 text-yellow-800"
                    }
                )}>
                    {if content.published {
                        i18n_content.get("content-manager-status-published")
                            .cloned()
                            .unwrap_or_else(|| "Published".to_string())
                    } else {
                        i18n_content.get("content-manager-status-draft")
                            .cloned()
                            .unwrap_or_else(|| "Draft".to_string())
                    }}
                </span>
            </td>
            <td class="p-4 text-sm text-gray-500">
                {content.updated_at.clone()}
            </td>
            <td class="p-4">
                <div class="flex items-center justify-center gap-2">
                    <button class="text-blue-600 hover:text-blue-800 text-sm font-medium">
                        {i18n_content.get("content-manager-action-edit")
                            .cloned()
                            .unwrap_or_else(|| "Edit".to_string())}
                    </button>
                    <button class={format!(
                        "text-sm font-medium {}",
                        if content.published {
                            "text-yellow-600 hover:text-yellow-800"
                        } else {
                            "text-green-600 hover:text-green-800"
                        }
                    )}>
                        {if content.published {
                            i18n_content.get("content-manager-action-unpublish")
                                .cloned()
                                .unwrap_or_else(|| "Unpublish".to_string())
                        } else {
                            i18n_content.get("content-manager-action-publish")
                                .cloned()
                                .unwrap_or_else(|| "Publish".to_string())
                        }}
                    </button>
                    <button class="text-red-600 hover:text-red-800 text-sm font-medium">
                        {i18n_content.get("content-manager-action-delete")
                            .cloned()
                            .unwrap_or_else(|| "Delete".to_string())}
                    </button>
                </div>
            </td>
        </tr>
    }
}

// Content creation request is now handled by UnifiedContentItem in shared crate

/// Generate configuration-driven mock content data
///
/// Instead of hardcoded data, this function creates mock content based on:
/// - Available content types from content-kinds.toml
/// - Current language for localized sample text
/// - i18n keys for sample content
fn generate_mock_content_from_config(
    content_types: &[String],
    language: &str,
    i18n_content: &HashMap<String, String>,
) -> Vec<ContentItemManager> {
    let mut mock_items = Vec::new();

    for (index, content_type) in content_types.iter().enumerate() {
        // Generate sample titles using i18n or fallback patterns
        let sample_title = i18n_content
            .get(&format!("content-manager-sample-{}-title", content_type))
            .cloned()
            .unwrap_or_else(|| {
                let first_char = content_type
                    .chars()
                    .nth(0)
                    .map(|c| c.to_uppercase().collect::<String>())
                    .unwrap_or_else(|| "S".to_string());
                format!(
                    "Sample {}{}",
                    first_char,
                    &content_type.get(1..).unwrap_or("")
                )
            });

        let sample_slug = format!("sample-{}-{}", content_type, index + 1);

        let sample_content = i18n_content
            .get(&format!("content-manager-sample-{}-content", content_type))
            .cloned()
            .unwrap_or_else(|| {
                format!(
                    "# Sample {}\n\nThis is sample content for demonstration.",
                    content_type
                )
            });

        let sample_excerpt = i18n_content
            .get(&format!("content-manager-sample-{}-excerpt", content_type))
            .cloned()
            .unwrap_or_else(|| {
                format!(
                    "Sample {} content for demonstration purposes.",
                    content_type
                )
            });

        let sample_category = i18n_content
            .get(&format!("content-manager-sample-category"))
            .cloned()
            .unwrap_or_else(|| "General".to_string());

        mock_items.push(ContentItemManager {
            id: (index + 1).to_string(),
            title: sample_title,
            slug: sample_slug,
            content: sample_content,
            content_type: content_type.clone(),
            language: language.to_string(),
            published: index % 2 == 0, // Alternate between published and draft
            tags: vec!["sample".to_string(), content_type.clone()],
            category: sample_category,
            excerpt: sample_excerpt,
            updated_at: format!("2024-01-{:02} 10:30:00", 15 - index), // Sample dates
        });
    }

    // If no content types available, return empty vector
    if mock_items.is_empty() {
        tracing::warn!(
            "No content types found in configuration - content manager will show empty state"
        );
    }

    mock_items
}
