<script lang="ts">
    import { onMount, untrack } from 'svelte';
    import { ae_loc, ae_api } from '$lib/stores/ae_stores';
    import { goto } from '$app/navigation';
    import { update_ae_obj__user, delete_ae_obj_id__user } from '$lib/ae_core/ae_core__user';
    import { editable_fields__user } from '$lib/ae_core/ae_core__user.editable_fields';
    import {
        ShieldCheck,
        Mail,
        User as UserIcon,
        ArrowLeft,
        Save,
        Trash2,
        Lock,
        Clock,
        Key,
        CircleCheck,
        CircleX,
        Fingerprint,
        Activity,
        Settings
    } from 'lucide-svelte';

    interface Props {
        data: any;
    }

    let { data }: Props = $props();
    let user = $state(untrack(() => data.user));
    let saving = $state(false);

    $effect(() => {
        user = data.user;
    });

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

    async function handle_save() {
        saving = true;
        const data_kv: any = {};
        editable_fields__user.forEach(field => {
            if (user[field] !== undefined) {
                data_kv[field] = user[field];
            }
        });

        const result = await update_ae_obj__user({
            api_cfg: $ae_api,
            user_id: user.user_id_random,
            data_kv,
            log_lvl: 1
        });

        if (result) {
            alert('User updated successfully');
        }
        saving = false;
    }

    async function handle_delete() {
        if (!confirm('Are you sure you want to disable this user account?')) return;

        const result = await delete_ae_obj_id__user({
            api_cfg: $ae_api,
            user_id: user.user_id_random,
            method: 'disable',
            log_lvl: 1
        });

        if (result) {
            goto('/core/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-4">
            <a class="btn btn-sm variant-soft-surface shadow-sm" href="/core/users">
                <ArrowLeft size={16} />
            </a>
            <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">
                    <UserIcon size={24} />
                </div>
                <div>
                    <h1 class="h2 font-black tracking-tight">{user.username}</h1>
                    <p class="text-[10px] uppercase font-bold tracking-widest opacity-50">UID: {user.user_id_random}</p>
                </div>
            </div>
        </div>
        <div class="flex gap-2">
            <button class="btn btn-sm variant-filled-error font-bold shadow-lg" onclick={handle_delete} disabled={saving}>
                <Trash2 size={16} class="mr-2" /> Disable
            </button>
            <button class="btn btn-sm variant-filled-primary font-bold shadow-lg" onclick={handle_save} disabled={saving}>
                {#if saving}
                    <span class="animate-spin mr-2">⏳</span>
                {:else}
                    <Save size={16} class="mr-2" />
                {/if}
                Save Changes
            </button>
        </div>
    </header>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- Main Info -->
        <div class="lg:col-span-2 space-y-6">
            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <UserIcon size={18} class="text-primary-500" /> Basic Profile
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="space-y-1">
                        <label class="label text-xs font-bold opacity-75" for="user-display-name">Display Name</label>
                        <input class="input variant-filled-surface rounded-lg p-2" id="user-display-name" type="text" bind:value={user.name} placeholder="Full Name" />
                    </div>
                    <div class="space-y-1">
                        <label class="label text-xs font-bold opacity-75" for="user-email">Email Address</label>
                        <input class="input variant-filled-surface rounded-lg p-2" id="user-email" type="email" bind:value={user.email} />
                    </div>
                    <div class="space-y-1 md:col-span-2">
                        <label class="label text-xs font-bold opacity-75" for="user-username">Username</label>
                        <div class="input-group input-group-divider grid-cols-[auto_1fr] variant-soft rounded-lg overflow-hidden border border-surface-500/20">
                            <div class="input-group-shim !pl-4 !pr-0"><Fingerprint size={16} /></div>
                            <input class="bg-transparent border-0 ring-0 focus:ring-0 font-mono opacity-60 p-2" id="user-username" type="text" bind:value={user.username} disabled />
                        </div>
                        <p class="text-[10px] opacity-50 mt-1 italic uppercase tracking-tighter">Username changes are currently restricted.</p>
                    </div>
                </div>
            </div>

            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <ShieldCheck size={18} class="text-secondary-500" /> System Permissions
                </h3>
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <label class="flex items-center space-x-3 card p-4 variant-soft-error cursor-pointer border border-error-500/20 hover:variant-filled-error transition-all group">
                        <input class="checkbox" type="checkbox" bind:checked={user.super} />
                        <div class="flex flex-col">
                            <span class="font-black uppercase text-xs tracking-widest">Super User</span>
                            <span class="text-[10px] opacity-70 group-hover:opacity-100">Full system override access</span>
                        </div>
                    </label>
                    <label class="flex items-center space-x-3 card p-4 variant-soft-warning cursor-pointer border border-warning-500/20 hover:variant-filled-warning transition-all group">
                        <input class="checkbox" type="checkbox" bind:checked={user.manager} />
                        <div class="flex flex-col">
                            <span class="font-black uppercase text-xs tracking-widest">Manager</span>
                            <span class="text-[10px] opacity-70 group-hover:opacity-100">Global account & user management</span>
                        </div>
                    </label>
                    <label class="flex items-center space-x-3 card p-4 variant-soft-primary cursor-pointer border border-primary-500/20 hover:variant-filled-primary transition-all group">
                        <input class="checkbox" type="checkbox" bind:checked={user.administrator} />
                        <div class="flex flex-col">
                            <span class="font-black uppercase text-xs tracking-widest">Administrator</span>
                            <span class="text-[10px] opacity-70 group-hover:opacity-100">Account-level administrative access</span>
                        </div>
                    </label>
                    <label class="flex items-center space-x-3 card p-4 variant-soft-secondary cursor-pointer border border-secondary-500/20 hover:variant-filled-secondary transition-all group">
                        <input class="checkbox" type="checkbox" bind:checked={user.verified} />
                        <div class="flex flex-col">
                            <span class="font-black uppercase text-xs tracking-widest">Verified User</span>
                            <span class="text-[10px] opacity-70 group-hover:opacity-100">Identity confirmed by staff</span>
                        </div>
                    </label>
                </div>
            </div>
        </div>

        <!-- Sidebar / Meta -->
        <div class="space-y-6">
            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Activity size={18} class="text-tertiary-500" /> Account Status
                </h3>
                <div class="space-y-4 py-2">
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={user.enable} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Login Enabled</span>
                    </label>
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={user.hide} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Hidden from Lists</span>
                    </label>
                    <label class="flex items-center space-x-3 cursor-pointer group">
                        <input class="checkbox" type="checkbox" bind:checked={user.allow_auth_key} />
                        <span class="text-sm font-bold opacity-70 group-hover:opacity-100 transition-opacity">Allow Email Auth Key</span>
                    </label>
                </div>
            </div>

            <div class="card p-6 space-y-4 shadow-xl variant-soft-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Lock size={18} class="text-surface-500" /> Linking Info
                </h3>
                <div class="space-y-3 text-xs">
                    <div class="flex justify-between items-center p-2 bg-black/5 rounded-lg">
                        <span class="font-bold opacity-50 uppercase tracking-tighter">Linked Person</span>
                        <span class="font-mono font-bold">
                            {#if user.person_id_random}
                                <a href="/core/people/{user.person_id_random}" class="text-primary-500 hover:underline">
                                    {user.person_id_random}
                                </a>
                            {:else}
                                <span class="italic text-error-500">Unlinked</span>
                            {/if}
                        </span>
                    </div>
                    <div class="flex justify-between items-center p-2 bg-black/5 rounded-lg">
                        <span class="font-bold opacity-50 uppercase tracking-tighter">Account Context</span>
                        <span class="font-mono font-bold">{user.account_id_random || '--'}</span>
                    </div>
                </div>
            </div>

            <div class="card p-6 space-y-4 shadow-xl variant-glass-surface border border-surface-500/10">
                <h3 class="h4 font-bold border-b border-surface-500/30 pb-2 flex items-center gap-2">
                    <Clock size={18} class="text-surface-500" /> Timestamps
                </h3>
                <div class="space-y-3 text-[10px] uppercase font-bold tracking-wider">
                    <div class="flex flex-col gap-1 opacity-60">
                        <span>Created On</span>
                        <span class="text-xs text-surface-900 dark:text-surface-100">{new Date(user.created_on).toLocaleString()}</span>
                    </div>
                    {#if user.updated_on}
                        <div class="flex flex-col gap-1 opacity-60 border-t border-surface-500/10 pt-2">
                            <span>Last Updated</span>
                            <span class="text-xs text-surface-900 dark:text-surface-100">{new Date(user.updated_on).toLocaleString()}</span>
                        </div>
                    {/if}
                </div>
            </div>
        </div>
    </div>
</div>
