// Example integration of Admin Dashboard into Leptos Router
// This file demonstrates how to integrate the admin dashboard into your main application

use crate::components::admin::AdminLayout;
use crate::i18n::{I18nProvider, use_i18n};
use crate::state::*;
use leptos::prelude::*;
use leptos_router::*;

/// Complete example of how to integrate the admin dashboard into your app
#[component]
pub fn AppWithAdminIntegration() -> impl IntoView {
    view! {
        <GlobalStateProvider>
            <ThemeProvider>
                <I18nProvider>
                    <ToastProvider>
                        <AuthProvider>
                            <UserProvider>
                                <Router>
                                    <Routes>
                                        // Public routes
                                        <Route path="/" view=HomePage />
                                        <Route path="/about" view=AboutPage />
                                        <Route path="/login" view=LoginPage />
                                        <Route path="/register" view=RegisterPage />

                                        // Protected admin routes
                                        <ProtectedRoute path="/admin/*" view=AdminLayout />
                                    </Routes>
                                </Router>
                            </UserProvider>
                        </AuthProvider>
                    </ToastProvider>
                </I18nProvider>
            </ThemeProvider>
        </GlobalStateProvider>
    }
}

/// Protected route component that checks authentication and admin privileges
#[component]
pub fn ProtectedRoute(
    path: &'static str,
    view: fn() -> impl IntoView + 'static,
) -> impl IntoView {
    let auth_context = use_context::<AuthContext>();
    let user_context = use_context::<UserContext>();

    let is_admin = create_memo(move |_| {
        match (auth_context, user_context) {
            (Some(auth), Some(user)) => {
                auth.is_authenticated() && user.has_role("admin")
            }
            _ => false,
        }
    });

    view! {
        <Route
            path=path
            view=move || {
                if is_admin.get() {
                    view().into_any()
                } else {
                    view! {
                        <div class="min-h-screen flex items-center justify-center bg-gray-50">
                            <div class="max-w-md w-full space-y-8">
                                <div class="text-center">
                                    <h2 class="mt-6 text-3xl font-extrabold text-gray-900">
                                        "Access Denied"
                                    </h2>
                                    <p class="mt-2 text-sm text-gray-600">
                                        "You need administrator privileges to access this area."
                                    </p>
                                    <div class="mt-6">
                                        <A href="/login" class="text-indigo-600 hover:text-indigo-500">
                                            "Sign in with an admin account"
                                        </A>
                                    </div>
                                </div>
                            </div>
                        </div>
                    }.into_any()
                }
            }
        />
    }
}

/// Alternative simpler integration if you want to handle routing manually
#[component]
pub fn SimpleAdminIntegration() -> impl IntoView {
    let location = use_location();
    let i18n = use_i18n();

    let is_admin_route = create_memo(move |_| {
        location.pathname.get().starts_with("/admin")
    });

    view! {
        <Show
            when=move || is_admin_route.get()
            fallback=move || view! {
                // Your regular app layout
                <div class="app-layout">
                    <header>"Regular App Header"</header>
                    <main>
                        <Routes>
                            <Route path="/" view=HomePage />
                            <Route path="/about" view=AboutPage />
                        </Routes>
                    </main>
                </div>
            }
        >
            // Full-screen admin layout
            <AdminLayout />
        </Show>
    }
}

/// Navigation component with admin link
#[component]
pub fn NavWithAdminLink() -> impl IntoView {
    let i18n = use_i18n();
    let auth_context = use_context::<AuthContext>();
    let user_context = use_context::<UserContext>();

    let is_admin = create_memo(move |_| {
        match (auth_context, user_context) {
            (Some(auth), Some(user)) => {
                auth.is_authenticated() && user.has_role("admin")
            }
            _ => false,
        }
    });

    view! {
        <nav class="bg-white shadow">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex">
                        <div class="flex-shrink-0 flex items-center">
                            <A href="/" class="text-xl font-bold text-gray-900">
                                "Your App"
                            </A>
                        </div>
                        <div class="hidden sm:ml-6 sm:flex sm:space-x-8">
                            <A href="/" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                                "Home"
                            </A>
                            <A href="/about" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                                "About"
                            </A>

                            // Admin link - only visible to admins
                            <Show when=move || is_admin.get()>
                                <A href="/admin" class="border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300 whitespace-nowrap py-2 px-1 border-b-2 font-medium text-sm">
                                    <svg class="w-4 h-4 mr-1 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    </svg>
                                    {move || i18n.t("admin.dashboard.title")}
                                </A>
                            </Show>
                        </div>
                    </div>
                </div>
            </div>
        </nav>
    }
}

/// Example context types you might need
pub struct AuthContext {
    pub user: ReadSignal<Option<User>>,
    pub token: ReadSignal<Option<String>>,
}

impl AuthContext {
    pub fn is_authenticated(&self) -> bool {
        self.user.get().is_some() && self.token.get().is_some()
    }
}

pub struct UserContext {
    pub roles: ReadSignal<Vec<String>>,
    pub permissions: ReadSignal<Vec<String>>,
}

impl UserContext {
    pub fn has_role(&self, role: &str) -> bool {
        self.roles.get().contains(&role.to_string())
    }

    pub fn has_permission(&self, permission: &str) -> bool {
        self.permissions.get().contains(&permission.to_string())
    }
}

#[derive(Clone, Debug)]
pub struct User {
    pub id: String,
    pub email: String,
    pub name: String,
    pub roles: Vec<String>,
}

// Placeholder components for the example
#[component]
fn HomePage() -> impl IntoView {
    view! { <div>"Home Page"</div> }
}

#[component]
fn AboutPage() -> impl IntoView {
    view! { <div>"About Page"</div> }
}

#[component]
fn LoginPage() -> impl IntoView {
    view! { <div>"Login Page"</div> }
}

#[component]
fn RegisterPage() -> impl IntoView {
    view! { <div>"Register Page"</div> }
}

/// RBAC Middleware example for server-side route protection
/// This would be used on the server to protect API endpoints
pub async fn require_admin_role(
    // request: Request,
    // next: Next,
) -> Result<(), String> {
    // Implementation would check JWT token for admin role
    // This is just a placeholder showing the concept

    // Extract JWT from request headers
    // Verify JWT signature
    // Check if user has 'admin' role
    // If yes, proceed; if no, return 403 Forbidden

    Ok(())
}

/// API endpoint protection example
pub async fn admin_api_handler() -> Result<String, String> {
    // This would be your actual API endpoint
    // The RBAC middleware would run before this

    Ok("Admin data".to_string())
}

/// Example of how to configure your server routes with RBAC
/// This would be in your server configuration
pub fn configure_admin_routes() {
    // axum example:
    // let admin_routes = Router::new()
    //     .route("/api/admin/users", get(get_users).post(create_user))
    //     .route("/api/admin/content", get(get_content).post(create_content))
    //     .route("/api/admin/roles", get(get_roles).post(create_role))
    //     .layer(middleware::from_fn(require_admin_role));
}

/// Complete setup example with all providers
#[component]
pub fn CompleteAppSetup() -> impl IntoView {
    view! {
        <GlobalStateProvider>
            <ThemeProvider>
                <I18nProvider>
                    <ToastProvider>
                        <AuthProvider>
                            <UserProvider>
                                <AppStateProvider>
                                    <Router>
                                        <NavWithAdminLink />
                                        <main>
                                            <Routes>
                                                // Public routes
                                                <Route path="/" view=HomePage />
                                                <Route path="/about" view=AboutPage />
                                                <Route path="/login" view=LoginPage />
                                                <Route path="/register" view=RegisterPage />

                                                // Admin routes (protected)
                                                <Route path="/admin/*" view=AdminLayout />

                                                // 404 fallback
                                                <Route path="/*any" view=NotFoundPage />
                                            </Routes>
                                        </main>
                                    </Router>
                                </AppStateProvider>
                            </UserProvider>
                        </AuthProvider>
                    </ToastProvider>
                </I18nProvider>
            </ThemeProvider>
        </GlobalStateProvider>
    }
}

#[component]
fn NotFoundPage() -> impl IntoView {
    view! {
        <div class="min-h-screen flex items-center justify-center bg-gray-50">
            <div class="text-center">
                <h1 class="text-6xl font-bold text-gray-900">"404"</h1>
                <p class="text-xl text-gray-600 mt-4">"Page not found"</p>
                <A href="/" class="mt-6 inline-block bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700">
                    "Go Home"
                </A>
            </div>
        </div>
    }
}
