//! Client-side Admin Layout Components
//!
//! Reactive implementation of admin layout components for client-side
//! rendering.

use ::rustelo_core_lib::i18n::{use_unified_i18n, UnifiedI18n};
use leptos::prelude::*;

use super::unified::AdminSection;
use crate::ui::spa_link::SpaLink;

#[component]
pub fn AdminLayout(
    current_path: ReadSignal<String>,
    #[prop(optional)] children: Option<Children>,
) -> impl IntoView {
    let i18n = use_unified_i18n();

    let current_section = Memo::new(move |_| {
        let pathname = current_path.get();
        match pathname.as_str() {
            "/admin/users" => AdminSection::Users,
            "/admin/roles" => AdminSection::Roles,
            "/admin/content" => AdminSection::Content,
            _ => AdminSection::Dashboard,
        }
    });

    view! {
        <div class="min-h-screen">
            <div class="flex">
                // Sidebar
                <div class="fixed inset-y-0 left-0 z-50 w-64 ds-bg ds-shadow-lg border-r ds-border transform transition-transform duration-300 ease-in-out lg:translate-x-0 lg:static lg:inset-0">
                    <div class="flex items-center justify-center h-16 px-4 bg-indigo-600">
                        <h1 class="text-xl font-bold ds-text">
                            {i18n.t("admin-dashboard")}
                        </h1>
                    </div>

                    <nav class="mt-8 px-4">
                        <AdminNavItem
                            section=AdminSection::Dashboard
                            current_section=current_section
                            i18n=i18n.clone()
                        />
                        <AdminNavItem
                            section=AdminSection::Users
                            current_section=current_section
                            i18n=i18n.clone()
                        />
                        <AdminNavItem
                            section=AdminSection::Roles
                            current_section=current_section
                            i18n=i18n.clone()
                        />
                        <AdminNavItem
                            section=AdminSection::Content
                            current_section=current_section
                            i18n=i18n.clone()
                        />
                    </nav>

                    // User info at bottom
                    <div class="absolute bottom-0 left-0 right-0 p-4 border-t ds-border">
                        <div class="flex items-center">
                            <div class="flex-shrink-0">
                                <div class="w-8 h-8 bg-indigo-600 ds-rounded-full flex items-center justify-center">
                                    <svg class="w-5 h-5 ds-text" fill="currentColor" viewBox="0 0 20 20">
                                        <path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path>
                                    </svg>
                                </div>
                            </div>
                            <div class="ml-3 flex-1 min-w-0">
                                <p class="ds-caption font-medium ds-text truncate">
                                    {i18n.t("admin-user")}
                                </p>
                                <p class="text-xs ds-text-muted truncate">
                                    "admin@example.com"
                                </p>
                            </div>
                            <div class="ml-2">
                                <button class="ds-text-muted hover:ds-text-secondary">
                                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                // Main content
                <div class="flex-1 lg:ml-64">
                    <main class="flex-1">
                        // Dynamic content based on current section - this would typically be handled by routing
                        {children.map(|c| c()).unwrap_or_else(|| {
                            view! {
                                <div class="p-8">
                                    <h2 class="text-2xl font-bold ds-text mb-4">
                                        {current_section.get().title(&i18n)}
                                    </h2>
                                    <p class="ds-text-secondary">
                                        {i18n.t("admin-content-placeholder")}
                                    </p>
                                </div>
                            }.into_any()
                        })}
                    </main>
                </div>
            </div>
        </div>
    }
}

#[component]
fn AdminNavItem(
    section: AdminSection,
    current_section: Memo<AdminSection>,
    i18n: UnifiedI18n,
) -> impl IntoView {
    let section_route = section.route().to_string();
    let section_icon = section.icon();
    let section_title = section.title(&i18n);
    let is_current = Memo::new(move |_| current_section.get() == section);

    view! {
        <SpaLink
            href=section_route
            class={
                let base_classes = "group flex items-center px-2 py-2 ds-caption font-medium ds-rounded-md transition-colors duration-150 ease-in-out mb-1";
                if is_current.get() {
                    format!("{} bg-indigo-100 text-indigo-700", base_classes)
                } else {
                    format!("{} ds-text-secondary hover:ds-text", base_classes)
                }
            }
        >
            <svg
                class={
                    let base_classes = "mr-3 flex-shrink-0 h-6 w-6";
                    if is_current.get() {
                        format!("{} text-indigo-500", base_classes)
                    } else {
                        format!("{} ds-text-muted group-hover:ds-text-muted", base_classes)
                    }
                }
                fill="none"
                viewBox="0 0 24 24"
                stroke="currentColor"
            >
                <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d=section_icon
                ></path>
            </svg>
            {section_title}
        </SpaLink>
    }
}

#[component]
pub fn AdminBreadcrumb(current_path: ReadSignal<String>) -> impl IntoView {
    let i18n = use_unified_i18n();

    let breadcrumb_items = Memo::new(move |_| {
        let pathname = current_path.get();
        let mut items = vec![(i18n.t("admin").to_string(), "/admin".to_string())];

        match pathname.as_str() {
            "/admin/users" => items.push((i18n.t("admin-users-title"), "/admin/users".to_string())),
            "/admin/roles" => items.push((i18n.t("admin-roles-title"), "/admin/roles".to_string())),
            "/admin/content" => {
                items.push((i18n.t("admin-content-title"), "/admin/content".to_string()))
            }
            _ => {}
        }

        items
    });

    view! {
        <nav class="flex mb-4" aria-label="Breadcrumb">
            <ol class="inline-flex items-center space-x-1 md:space-x-3">
                <For
                    each=move || breadcrumb_items.get()
                    key=|(title, _)| title.clone()
                    children=move |(title, href)| {
                        let items = breadcrumb_items.get();
                        let is_last = items.last().map(|(t, _)| t.as_str()) == Some(&title);

                        view! {
                            <li class="inline-flex items-center">
                                {if is_last {
                                    view! {
                                        <span class="ml-1 ds-caption font-medium ds-text-muted md:ml-2">
                                            {title}
                                        </span>
                                    }.into_any()
                                } else {
                                    view! {
                                        <SpaLink
                                            href=href
                                            class="inline-flex items-center ds-caption font-medium ds-text-secondary hover:text-blue-600".to_string()
                                        >
                                            {title}
                                        </SpaLink>
                                        <svg class="w-6 h-6 ds-text-muted ml-1" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path>
                                        </svg>
                                    }.into_any()
                                }}
                            </li>
                        }
                    }
                />
            </ol>
        </nav>
    }
}

#[component]
pub fn AdminHeader(
    #[prop(optional)] title: Option<String>,
    #[prop(optional)] subtitle: Option<String>,
    #[prop(optional)] actions: Option<Children>,
) -> impl IntoView {
    let i18n = use_unified_i18n();
    let title_text = title.unwrap_or_else(|| i18n.t("admin"));
    let subtitle_text = subtitle.unwrap_or_default();
    let has_subtitle = !subtitle_text.is_empty();

    view! {
        <div class="ds-bg shadow">
            <div class="px-4 sm:px-6 lg:max-w-6xl lg:mx-auto lg:px-8">
                <div class="py-6 md:flex md:items-center md:justify-between lg:border-t lg:ds-border">
                    <div class="flex-1 min-w-0">
                        <div class="flex items-center">
                            <div>
                                <div class="flex items-center">
                                    <h1 class="ml-3 text-2xl font-bold leading-7 ds-text sm:leading-9 sm:truncate">
                                        {title_text}
                                    </h1>
                                </div>
                                <Show when=move || has_subtitle>
                                    <dl class="mt-6 flex flex-col sm:ml-3 sm:mt-1 sm:flex-row sm:flex-wrap">
                                        <dd class="ds-caption ds-text-muted sm:mr-6">
                                            {subtitle_text.clone()}
                                        </dd>
                                    </dl>
                                </Show>
                            </div>
                        </div>
                    </div>
                    <div class="mt-6 flex space-x-3 md:mt-0 md:ml-4">
                        {actions.map(|a| a()).unwrap_or_else(|| view! {}.into_any())}
                    </div>
                </div>
            </div>
        </div>
    }
}

#[component]
pub fn AdminCard(
    #[prop(optional)] title: Option<String>,
    #[prop(optional)] class: Option<String>,
    children: Children,
) -> impl IntoView {
    let class_str = class.unwrap_or_default();
    let title_str = title.unwrap_or_default();
    let has_title = !title_str.is_empty();

    view! {
        <div class=format!(
            "ds-bg overflow-hidden shadow ds-rounded-lg {}",
            class_str
        )>
            <Show when=move || has_title>
                <div class="px-4 py-5 sm:p-6 border-b ds-border">
                    <h3 class="ds-body leading-6 font-medium ds-text">
                        {title_str.clone()}
                    </h3>
                </div>
            </Show>
            <div class="px-4 py-5 sm:p-6">
                {children()}
            </div>
        </div>
    }
}

#[component]
pub fn AdminEmptyState(
    #[prop(optional)] icon: Option<String>,
    #[prop(optional)] title: Option<String>,
    #[prop(optional)] description: Option<String>,
    #[prop(optional)] action: Option<Children>,
) -> impl IntoView {
    let i18n = use_unified_i18n();
    let icon_str = icon.unwrap_or_default();
    let title_str = title.unwrap_or_else(|| i18n.t("admin-no-items"));
    let description_str = description.unwrap_or_default();
    let has_icon = !icon_str.is_empty();
    let has_description = !description_str.is_empty();

    view! {
        <div class="text-center py-12">
            <Show when=move || has_icon>
                <svg class="mx-auto h-12 w-12 ds-text-muted" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d=icon_str.clone()></path>
                </svg>
            </Show>
            <h3 class="mt-2 ds-caption font-medium ds-text">
                {title_str}
            </h3>
            <Show when=move || has_description>
                <p class="mt-1 ds-caption ds-text-muted">
                    {description_str.clone()}
                </p>
            </Show>
            <div class="mt-6">
                {action.map(|a| a()).unwrap_or_else(|| view! {}.into_any())}
            </div>
        </div>
    }
}
