<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 { Plus, Search, User, ShieldCheck, Mail, Globe, Landmark, ListFilter, X, Fingerprint, Activity } 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 p-4 space-y-6">
    <header class="flex justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10">
        <div class="flex items-center gap-2">
            <div class="p-2 bg-primary-500/10 rounded-lg">
                <ShieldCheck size={24} class="text-primary-500" />
            </div>
            <h1 class="h2 font-black tracking-tight">User Management</h1>
        </div>
        <button class="btn btn-sm variant-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 p-6 shadow-xl variant-glass-surface border border-surface-500/10 space-y-4">
        <div class="flex flex-wrap gap-6 items-end">
            <div class="flex-1 min-w-[280px] space-y-1">
                <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Search Users</span>
                <div class="flex bg-surface-200-700-token rounded-lg overflow-hidden border border-surface-500/20 shadow-inner group focus-within:ring-2 focus-within:ring-primary-500/50 transition-all">
                    <div class="flex items-center justify-center px-4 bg-surface-300-600-token border-r border-surface-500/20">
                        <Search size={18} class="opacity-50" />
                    </div>
                    <input
                        class="bg-transparent border-0 ring-0 focus:ring-0 p-3 grow placeholder:opacity-50"
                        type="search"
                        bind:value={qry_str}
                        placeholder="Search username or email..."
                        onkeydown={(e) => e.key === 'Enter' && load_users()}
                    />
                    <button class="variant-filled-primary font-bold px-10 py-3 hover:brightness-110 transition-all border-l border-surface-500/20 flex items-center justify-center min-w-[100px]" onclick={load_users} disabled={loading}>
                        {#if loading}
                            <span class="animate-spin text-xl">⏳</span>
                        {:else}
                            <span class="whitespace-nowrap tracking-wide">Go</span>
                        {/if}
                    </button>
                </div>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div class="space-y-1">
                    <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Scope</span>
                    <select class="select variant-filled-surface rounded-lg text-sm border border-surface-500/20 p-2" 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 block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Status</span>
                    <select class="select variant-filled-surface rounded-lg text-sm border border-surface-500/20 p-2" 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 p-8 flex justify-center items-center h-64">
            <div class="placeholder animate-pulse w-full h-full rounded-2xl"></div>
        </div>
    {:else if user_li.length === 0}
        <div class="card p-12 text-center variant-glass-surface border-2 border-dashed border-surface-500/20 rounded-2xl">
            <Fingerprint size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Users Found</h3>
            <p class="opacity-60 max-w-xs mx-auto mt-2">Try adjusting your search or scope filters.</p>
        </div>
    {:else}
        <div class="card p-6 variant-glass-surface shadow-xl border border-surface-500/10">
            <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 mb-6 flex items-center gap-2">
                <ListFilter size={18} class="text-secondary-500" />
                Directory Results
                <span class="badge variant-soft-secondary ml-auto">{user_li.length} found</span>
            </h3>

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

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

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