<script lang="ts">
import { onMount } from 'svelte';
import {
    load_ae_obj_li__user,
    create_ae_obj__user
} from '$lib/ae_core/ae_core__user';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import { goto } from '$app/navigation';
import {
    Activity,
    Fingerprint,
    Globe,
    Landmark,
    ListFilter,
    Mail,
    Plus,
    Search,
    ShieldCheck,
    User,
    X
} from '@lucide/svelte';
let user_li: any[] = $state([]);
let loading = $state(true);
let qry_str = $state('');
let qry_enabled = $state('all');
let qry_account_scope = $state('all'); // 'all', 'account', 'global'
let show_add_form = $state(false);

async function load_users() {
    loading = true;

    let for_obj_id: string | null = $ae_loc.account_id;
    let include_global = true;

    if (qry_account_scope === 'account') {
        include_global = false;
    } else if (qry_account_scope === 'global') {
        for_obj_id = null;
        include_global = true; // This will trigger the (account_id IS NULL) logic in the search if no qry_str
    }

    user_li = await load_ae_obj_li__user({
        api_cfg: $ae_api,
        for_obj_id: for_obj_id,
        include_global: include_global,
        qry_str: qry_str || null,
        enabled: qry_enabled as any,
        log_lvl: 1
    });
    loading = false;
}

onMount(() => {
    if (!$ae_loc.manager_access) {
        goto('/core');
        return;
    }
    load_users();
});

async function handle_add_user() {
    const username = prompt('Enter new username:');
    if (!username) return;
    const email = prompt('Enter email address:');

    // Link to account if scope is 'account' or 'all', otherwise create global user
    const account_id =
        qry_account_scope === 'global' ? undefined : $ae_loc.account_id;

    await create_ae_obj__user({
        api_cfg: $ae_api,
        account_id: account_id,
        data_kv: { username, email, enable: true },
        log_lvl: 1
    });
    load_users();
}
</script>

<div class="container mx-auto space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex items-center justify-between rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-2">
            <div class="bg-primary-500/10 rounded-lg p-2">
                <ShieldCheck size={24} class="text-primary-500" />
            </div>
            <h1 class="h2 font-black tracking-tight">User Management</h1>
        </div>
        <button
            class="btn btn-sm preset-filled-primary font-bold shadow-lg"
            onclick={() => (show_add_form = !show_add_form)}>
            {#if show_add_form}
                <X size={16} class="mr-2" /> Cancel
            {:else}
                <Plus size={16} class="mr-2" /> Add User
            {/if}
        </button>
    </header>

    <div
        class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
        <div class="flex flex-wrap items-end gap-6">
            <div class="min-w-[280px] flex-1 space-y-1">
                <span
                    class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                    >Search Users</span>
                <div
                    class="bg-surface-200-700-token border-surface-500/20 group focus-within:ring-primary-500/50 flex overflow-hidden rounded-lg border shadow-inner transition-all focus-within:ring-2">
                    <div
                        class="bg-surface-300-600-token border-surface-500/20 flex items-center justify-center border-r px-4">
                        <Search size={18} class="opacity-50" />
                    </div>
                    <input
                        class="grow border-0 bg-transparent p-3 ring-0 placeholder:opacity-50 focus:ring-0"
                        type="search"
                        bind:value={qry_str}
                        placeholder="Search username or email..."
                        onkeydown={(e) => e.key === 'Enter' && load_users()} />
                    <button
                        class="preset-filled-primary border-surface-500/20 flex min-w-[100px] items-center justify-center border-l px-10 py-3 font-bold transition-all hover:brightness-110"
                        onclick={load_users}
                        disabled={loading}>
                        {#if loading}
                            <span class="animate-spin text-xl">⏳</span>
                        {:else}
                            <span class="tracking-wide whitespace-nowrap"
                                >Go</span>
                        {/if}
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                <div class="space-y-1">
                    <span
                        class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                        >Scope</span>
                    <select
                        class="select preset-filled-surface border-surface-500/20 rounded-lg border p-2 text-sm"
                        bind:value={qry_account_scope}
                        onchange={load_users}>
                        <option value="all">All (Current + Global)</option>
                        <option value="account">Account Only</option>
                        <option value="global">Global Only</option>
                    </select>
                </div>

                <div class="space-y-1">
                    <span
                        class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                        >Status</span>
                    <select
                        class="select preset-filled-surface border-surface-500/20 rounded-lg border p-2 text-sm"
                        bind:value={qry_enabled}
                        onchange={load_users}>
                        <option value="all">All</option>
                        <option value="enabled">Enabled</option>
                        <option value="not_enabled">Disabled</option>
                    </select>
                </div>
            </div>
        </div>
    </div>

    {#if loading}
        <div class="card flex h-64 items-center justify-center p-8">
            <div class="placeholder h-full w-full animate-pulse rounded-2xl">
            </div>
        </div>
    {:else if user_li.length === 0}
        <div
            class="card preset-tonal-surface border-surface-500/20 rounded-2xl border-2 border-dashed p-12 text-center">
            <Fingerprint size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Users Found</h3>
            <p class="mx-auto mt-2 max-w-xs opacity-60">
                Try adjusting your search or scope filters.
            </p>
        </div>
    {:else}
        <div
            class="card preset-tonal-surface border-surface-500/10 border p-6 shadow-xl">
            <h3
                class="h4 border-surface-500/30 mb-6 flex items-center gap-2 border-b pb-2 font-bold">
                <ListFilter size={18} class="text-secondary-500" />
                Directory Results
                <span class="badge preset-tonal-secondary ml-auto"
                    >{user_li.length} found</span>
            </h3>

            <div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
                {#each user_li as user (user.user_id_random)}
                    <div
                        class="card preset-tonal-surface border-surface-500/10 hover:border-primary-500/30 group space-y-4 border p-5 shadow-md transition-all">
                        <header class="flex items-start justify-between">
                            <div class="flex items-center gap-3">
                                <div
                                    class="avatar preset-filled-primary flex h-12 w-12 items-center justify-center rounded-full shadow-inner transition-transform group-hover:scale-110">
                                    <User size={24} />
                                </div>
                                <div>
                                    <p class="font-black tracking-tight">
                                        {user.username}
                                    </p>
                                    <p
                                        class="text-[10px] font-bold uppercase opacity-50">
                                        {user.name || 'No Display Name'}
                                    </p>
                                </div>
                            </div>
                            <div class="flex flex-col items-end gap-1">
                                {#if user.super}
                                    <span
                                        class="badge preset-filled-error text-[8px] font-bold uppercase"
                                        >Super</span>
                                {:else if user.manager}
                                    <span
                                        class="badge preset-filled-warning text-[8px] font-bold uppercase"
                                        >Manager</span>
                                {/if}
                                {#if !user.account_id && !user.account_id_random}
                                    <span
                                        class="badge preset-tonal-secondary flex items-center gap-1 text-[8px] font-bold uppercase">
                                        <Globe size={8} /> Global
                                    </span>
                                {:else}
                                    <span
                                        class="badge preset-tonal-primary flex items-center gap-1 text-[8px] font-bold uppercase">
                                        <Landmark size={8} /> Account
                                    </span>
                                {/if}
                            </div>
                        </header>

                        <div class="space-y-2">
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2 text-xs opacity-70">
                                <Mail size={14} class="text-primary-500" />
                                <span class="truncate"
                                    >{user.email || '--'}</span>
                            </div>
                            <div
                                class="flex items-center gap-2 rounded-lg bg-black/5 p-2 text-xs opacity-70">
                                <Activity
                                    size={14}
                                    class="text-secondary-500" />
                                <span class="font-mono"
                                    >{user.user_id_random}</span>
                            </div>
                        </div>

                        <a
                            class="btn btn-sm preset-filled-primary w-full font-bold shadow-lg transition-all group-hover:brightness-110"
                            href="/core/users/{user.user_id_random}">
                            Manage User
                        </a>
                    </div>
                {/each}
            </div>
        </div>
    {/if}
</div>
