// use crate::components::*;
use crate::i18n::use_i18n;
use leptos::prelude::*;
// use leptos_router::*;
use serde::{Deserialize, Serialize};
// use std::collections::HashMap;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_futures::spawn_local;

#[cfg(not(target_arch = "wasm32"))]
fn spawn_local<F>(_fut: F)
where
    F: std::future::Future<Output = ()> + 'static,
{
    // On server side, don't execute async operations that require browser APIs
}

#[derive(Clone, Debug, Default, Serialize, Deserialize)]
struct AdminStats {
    total_users: u32,
    active_users: u32,
    content_items: u32,
    total_roles: u32,
    pending_approvals: u32,
    system_health: String,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
struct RecentActivity {
    id: String,
    user_email: String,
    action: String,
    resource_type: String,
    timestamp: String,
    status: String,
}

#[component]
pub fn AdminDashboard() -> impl IntoView {
    let i18n = use_i18n();
    let (stats, set_stats) = signal(AdminStats::default());
    let (recent_activity, set_recent_activity) = signal(Vec::<RecentActivity>::new());
    let (loading, set_loading) = signal(true);
    let (error, set_error) = signal(None::<String>);

    // Fetch dashboard data on mount
    Effect::new(move |_| {
        spawn_local(async move {
            set_loading.set(true);
            set_error.set(None);

            match fetch_dashboard_data().await {
                Ok((stats_data, activities_data)) => {
                    set_stats.set(stats_data);
                    set_recent_activity.set(activities_data);
                    set_loading.set(false);
                }
                Err(e) => {
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    });

    let refresh_data = move |_| {
        spawn_local(async move {
            set_loading.set(true);
            match fetch_dashboard_data().await {
                Ok((stats_data, activities_data)) => {
                    set_stats.set(stats_data);
                    set_recent_activity.set(activities_data);
                    set_loading.set(false);
                }
                Err(e) => {
                    set_error.set(Some(e));
                    set_loading.set(false);
                }
            }
        });
    };

    view! {
        <div class="min-h-screen bg-gray-50">
            <div class="py-6">
                <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                    // Header
                    <div class="pb-5 border-b border-gray-200">
                        <div class="flex items-center justify-between">
                            <div>
                                <h1 class="text-3xl font-bold leading-tight text-gray-900">
                                   {i18n.t("admin-dashboard")}
                                </h1>
                                <p class="mt-2 text-sm text-gray-600">
                                    {i18n.t("overview-of-your-system")}
                                </p>
                            </div>
                            <button
                                class="bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                                on:click=refresh_data
                                disabled=move || loading.get()
                            >
                                <Show when=move || loading.get()>
                                    <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                                    </svg>
                                </Show>
                                <Show when=move || !loading.get()>
                                    <svg class="w-5 h-5 mr-2 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                                    </svg>
                                </Show>
                               {i18n.t("refresh")}
                            </button>
                        </div>
                    </div>

                    // Error Alert
                    <Show when=move || error.get().is_some()>
                        <div class="mt-4 bg-red-50 border border-red-200 rounded-md p-4">
                            <div class="flex">
                                <svg class="h-5 w-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd"></path>
                                </svg>
                                <div class="ml-3">
                                    <p class="text-sm text-red-800">
                                        {move || error.get().unwrap_or_default()}
                                    </p>
                                </div>
                            </div>
                        </div>
                    </Show>

                    <Show
                        when=move || !loading.get()
                        fallback=|| view! { <AdminDashboardSkeleton /> }
                    >
                        <div class="mt-6 space-y-6">
                            <AdminStatsCards stats=stats />
                            <AdminQuickActions />
                            <AdminRecentActivity activities=recent_activity />
                        </div>
                    </Show>
                </div>
            </div>
        </div>
    }
}

#[component]
fn AdminStatsCards(stats: ReadSignal<AdminStats>) -> impl IntoView {
    let i18n = use_i18n();
    view! {
        <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
            // Total Users Card
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">
                                    {i18n.t("total-users")}
                                </dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    {move || stats.get().total_users.to_string()}
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            // Active Users Card
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">
                                    {i18n.t("active-users")}
                                </dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    {move || stats.get().active_users.to_string()}
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            // Content Items Card
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">
                                    {i18n.t("content-items")}
                                </dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    {move || stats.get().content_items.to_string()}
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>

            // Total Roles Card
            <div class="bg-white overflow-hidden shadow rounded-lg">
                <div class="p-5">
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <svg class="h-8 w-8 text-purple-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                            </svg>
                        </div>
                        <div class="ml-5 w-0 flex-1">
                            <dl>
                                <dt class="text-sm font-medium text-gray-500 truncate">
                                    {i18n.t("total-roles")}
                                </dt>
                                <dd class="text-lg font-medium text-gray-900">
                                    {move || stats.get().total_roles.to_string()}
                                </dd>
                            </dl>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    }
}

#[component]
fn AdminQuickActions() -> impl IntoView {
    let i18n = use_i18n();
    view! {
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900">
                    "Quick Actions"
                </h3>
                <div class="mt-5 grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
                    <a href="/admin/users" class="relative block w-full border-2 border-gray-300 border-dashed rounded-lg p-6 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4.354a4 4 0 110 5.292M15 21H3v-1a6 6 0 0112 0v1zm0 0h6v-1a6 6 0 00-9-5.197m13.5-9a2.5 2.5 0 11-5 0 2.5 2.5 0 015 0z"></path>
                        </svg>
                        <span class="mt-2 block text-sm font-medium text-gray-900">
                            {i18n.t("manage-users")}
                        </span>
                    </a>

                    <a href="/admin/roles" class="relative block w-full border-2 border-gray-300 border-dashed rounded-lg p-6 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                        </svg>
                        <span class="mt-2 block text-sm font-medium text-gray-900">
                            {i18n.t("manage-roles")}
                        </span>
                    </a>

                    <a href="/admin/content" class="relative block w-full border-2 border-gray-300 border-dashed rounded-lg p-6 text-center hover:border-gray-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-all">
                        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                        </svg>
                        <span class="mt-2 block text-sm font-medium text-gray-900">
                            {i18n.t("manage-content")}
                        </span>
                    </a>
                </div>
            </div>
        </div>
    }
}

#[component]
fn AdminRecentActivity(activities: ReadSignal<Vec<RecentActivity>>) -> impl IntoView {
    let i18n = use_i18n();
    view! {
        <div class="bg-white shadow rounded-lg">
            <div class="px-4 py-5 sm:p-6">
                <h3 class="text-lg leading-6 font-medium text-gray-900">
                    "Recent Activity"
                </h3>
                <div class="mt-5">
                    <div class="flow-root">
                        <ul class="-my-5 divide-y divide-gray-200">
                            <Show
                                when=move || !activities.get().is_empty()
                                fallback=move || view! {
                                    <li class="py-4">
                                        <div class="flex items-center space-x-4">
                                            <div class="flex-shrink-0">
                                                <div class="h-8 w-8 rounded-full bg-gray-200 flex items-center justify-center">
                                                    <svg class="h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4"></path>
                                                    </svg>
                                                </div>
                                            </div>
                                            <div class="flex-1 min-w-0">
                                                <p class="text-sm font-medium text-gray-900">
                                                    {i18n.t("no-recent-activity")}
                                                </p>
                                                <p class="text-sm text-gray-500">
                                                    {i18n.t("activity-will-appear-here")}
                                                </p>
                                            </div>
                                        </div>
                                    </li>
                                }
                            >
                                <For
                                    each=move || activities.get()
                                    key=|activity| activity.id.clone()
                                    children=move |activity| {
                                        view! {
                                            <li class="py-4">
                                                <div class="flex items-center space-x-4">
                                                    <div class="flex-shrink-0">
                                                        <div class="h-8 w-8 rounded-full bg-indigo-100 flex items-center justify-center">
                                                            <span class="text-sm font-medium text-indigo-600">
                                                                {activity.user_email.chars().next().unwrap_or('U')}
                                                            </span>
                                                        </div>
                                                    </div>
                                                    <div class="flex-1 min-w-0">
                                                        <p class="text-sm font-medium text-gray-900 truncate">
                                                            {activity.action.clone()}
                                                        </p>
                                                        <p class="text-sm text-gray-500 truncate">
                                                            {activity.user_email.clone()}
                                                        </p>
                                                    </div>
                                                    <div class="flex-shrink-0 text-sm text-gray-500">
                                                        {activity.timestamp.clone()}
                                                    </div>
                                                </div>
                                            </li>
                                        }
                                    }
                                />
                            </Show>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    }
}

#[component]
fn AdminDashboardSkeleton() -> impl IntoView {
    view! {
        <div class="mt-6 animate-pulse">
            // Stats Cards Skeleton
            <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4">
                {(0..4).map(|_| view! {
                    <div class="bg-white overflow-hidden shadow rounded-lg">
                        <div class="p-5">
                            <div class="flex items-center">
                                <div class="flex-shrink-0">
                                    <div class="h-8 w-8 bg-gray-200 rounded"></div>
                                </div>
                                <div class="ml-5 w-0 flex-1">
                                    <div class="h-4 bg-gray-200 rounded w-3/4"></div>
                                    <div class="h-6 bg-gray-200 rounded w-1/2 mt-2"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                }).collect_view()}
            </div>

            // Quick Actions Skeleton
            <div class="mt-6 bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="h-6 bg-gray-200 rounded w-1/4 mb-5"></div>
                    <div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
                        {(0..3).map(|_| view! {
                            <div class="border-2 border-gray-200 rounded-lg p-6">
                                <div class="h-12 w-12 bg-gray-200 rounded mx-auto"></div>
                                <div class="h-4 bg-gray-200 rounded w-3/4 mx-auto mt-2"></div>
                            </div>
                        }).collect_view()}
                    </div>
                </div>
            </div>

            // Recent Activity Skeleton
            <div class="mt-6 bg-white shadow rounded-lg">
                <div class="px-4 py-5 sm:p-6">
                    <div class="h-6 bg-gray-200 rounded w-1/4 mb-5"></div>
                    <div class="space-y-4">
                        {(0..5).map(|_| view! {
                            <div class="py-4">
                                <div class="flex items-center space-x-4">
                                    <div class="h-8 w-8 bg-gray-200 rounded-full"></div>
                                    <div class="flex-1">
                                        <div class="h-4 bg-gray-200 rounded w-3/4"></div>
                                        <div class="h-3 bg-gray-200 rounded w-1/2 mt-2"></div>
                                    </div>
                                    <div class="h-3 bg-gray-200 rounded w-16"></div>
                                </div>
                            </div>
                        }).collect_view()}
                    </div>
                </div>
            </div>
        </div>
    }
}

// API functions
async fn fetch_dashboard_data() -> Result<(AdminStats, Vec<RecentActivity>), String> {
    // This would normally make actual API calls to the backend
    // For now, return mock data

    let stats = AdminStats {
        total_users: 147,
        active_users: 89,
        content_items: 42,
        total_roles: 5,
        pending_approvals: 3,
        system_health: "Healthy".to_string(),
    };

    let activities = vec![
        RecentActivity {
            id: "1".to_string(),
            user_email: "admin@example.com".to_string(),
            action: "User Login".to_string(),
            resource_type: "auth".to_string(),
            timestamp: "2 hours ago".to_string(),
            status: "success".to_string(),
        },
        RecentActivity {
            id: "2".to_string(),
            user_email: "user@example.com".to_string(),
            action: "Content Update".to_string(),
            resource_type: "content".to_string(),
            timestamp: "4 hours ago".to_string(),
            status: "success".to_string(),
        },
    ];

    Ok((stats, activities))
}
