<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 {
    Activity,
    ArrowLeft,
    CircleCheck,
    CircleX,
    Clock,
    FingerprintPattern,
    Key,
    Lock,
    Mail,
    Save,
    Settings,
    ShieldCheck,
    Trash2,
    User as UserIcon
} from '@lucide/svelte';
interface Props {
    data: any;
}

let { data }: Props = $props();
let user = $state(untrack(() => data.user));
let saving = $state(false);
let save_success = $state(false);
let confirm_action = $state<string | null>(null);

$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,
        data_kv,
        log_lvl: 1
    });

    if (result) {
        save_success = true;
        setTimeout(() => (save_success = false), 2500);
    }
    saving = false;
}

async function handle_delete() {
    if (confirm_action !== 'disable_user') {
        confirm_action = 'disable_user';
        return;
    }
    confirm_action = null;

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

    if (result) {
        goto('/core/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-4">
            <a
                class="btn btn-sm preset-tonal-surface shadow-sm"
                href="/core/users">
                <ArrowLeft size={16} />
            </a>
            <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">
                    <UserIcon size={24} />
                </div>
                <div>
                    <h1 class="h2 font-black tracking-tight">
                        {user.username}
                    </h1>
                    <p
                        class="text-[10px] font-bold tracking-widest uppercase opacity-50">
                        UID: {user.user_id}
                    </p>
                </div>
            </div>
        </div>
        <div class="flex items-center gap-2">
            {#if confirm_action === 'disable_user'}
                <span class="text-sm font-bold text-red-600">Disable this user?</span>
                <button
                    class="btn btn-sm preset-filled-error font-bold shadow-lg"
                    onclick={handle_delete}
                    disabled={saving}>
                    <Trash2 size={16} class="mr-2" /> Confirm Disable
                </button>
                <button
                    class="btn btn-sm preset-tonal-surface"
                    onclick={() => (confirm_action = null)}>
                    Cancel
                </button>
            {:else}
                <button
                    class="btn btn-sm preset-filled-error font-bold shadow-lg"
                    onclick={handle_delete}
                    disabled={saving}>
                    <Trash2 size={16} class="mr-2" /> Disable
                </button>
            {/if}
            {#if save_success}
                <span class="flex items-center gap-1 text-sm font-bold text-green-600">
                    <CircleCheck size={16} /> Saved
                </span>
            {/if}
            <button
                class="btn btn-sm preset-filled-primary font-bold shadow-lg"
                onclick={handle_save}
                disabled={saving}>
                {#if saving}
                    <span class="mr-2 animate-spin">⏳</span>
                {:else}
                    <Save size={16} class="mr-2" />
                {/if}
                Save Changes
            </button>
        </div>
    </header>

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

            <div
                class="card preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
                <h3
                    class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                    <ShieldCheck size={18} class="text-secondary-500" /> System Permissions
                </h3>
                <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
                    <label
                        class="card preset-tonal-error border-error-500/20 hover:preset-filled-error group flex cursor-pointer items-center space-x-3 border p-4 transition-all">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.super} />
                        <div class="flex flex-col">
                            <span
                                class="text-xs font-black tracking-widest uppercase"
                                >Super User</span>
                            <span
                                class="text-[10px] opacity-70 group-hover:opacity-100"
                                >Full system override access</span>
                        </div>
                    </label>
                    <label
                        class="card preset-tonal-warning border-warning-500/20 hover:preset-filled-warning group flex cursor-pointer items-center space-x-3 border p-4 transition-all">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.manager} />
                        <div class="flex flex-col">
                            <span
                                class="text-xs font-black tracking-widest uppercase"
                                >Manager</span>
                            <span
                                class="text-[10px] opacity-70 group-hover:opacity-100"
                                >Global account & user management</span>
                        </div>
                    </label>
                    <label
                        class="card preset-tonal-primary border-primary-500/20 hover:preset-filled-primary group flex cursor-pointer items-center space-x-3 border p-4 transition-all">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.administrator} />
                        <div class="flex flex-col">
                            <span
                                class="text-xs font-black tracking-widest uppercase"
                                >Administrator</span>
                            <span
                                class="text-[10px] opacity-70 group-hover:opacity-100"
                                >Account-level administrative access</span>
                        </div>
                    </label>
                    <label
                        class="card preset-tonal-secondary border-secondary-500/20 hover:preset-filled-secondary group flex cursor-pointer items-center space-x-3 border p-4 transition-all">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.verified} />
                        <div class="flex flex-col">
                            <span
                                class="text-xs font-black tracking-widest uppercase"
                                >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 preset-tonal-surface border-surface-500/10 space-y-4 border p-6 shadow-xl">
                <h3
                    class="h4 border-surface-500/30 flex items-center gap-2 border-b pb-2 font-bold">
                    <Activity size={18} class="text-tertiary-500" /> Account Status
                </h3>
                <div class="space-y-4 py-2">
                    <label
                        class="group flex cursor-pointer items-center space-x-3">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.enable} />
                        <span
                            class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                            >Login Enabled</span>
                    </label>
                    <label
                        class="group flex cursor-pointer items-center space-x-3">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.hide} />
                        <span
                            class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                            >Hidden from Lists</span>
                    </label>
                    <label
                        class="group flex cursor-pointer items-center space-x-3">
                        <input
                            class="checkbox"
                            type="checkbox"
                            bind:checked={user.allow_auth_key} />
                        <span
                            class="text-sm font-bold opacity-70 transition-opacity group-hover:opacity-100"
                            >Allow Email Auth Key</span>
                    </label>
                </div>
            </div>

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

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