<script lang="ts">
/** @type {import('./$types').PageData} */
import { onMount } from 'svelte';
import { qry__activity_log } from '$lib/ae_core/ae_core__activity_log';
import { ae_api, ae_loc } from '$lib/stores/ae_stores';
import {
    Activity,
    Calendar,
    Clock,
    History,
    ListFilter,
    RefreshCcw,
    Search,
    ShieldCheck,
    Tag,
    User
} from '@lucide/svelte';
import { ae_util } from '$lib/ae_utils/ae_utils';

// State
let log_li: any[] = $state([]);
let loading = $state(true);
let qry_str = $state('');
let limit = $state(50);

/**
 * Fetches activity logs from the API based on current filters.
 */
async function load_logs() {
    if (!$ae_loc.account_id) return;
    loading = true;

    const results = await qry__activity_log({
        api_cfg: $ae_api,
        account_id: $ae_loc.account_id,
        qry_str: qry_str || undefined,
        enabled: 'all',
        hidden: 'all',
        limit: limit,
        log_lvl: 1
    });

    log_li = results || [];
    loading = false;
}

onMount(() => {
    load_logs();
});

/**
 * Handles the search form submission.
 */
function handle_search(e: Event) {
    e.preventDefault();
    load_logs();
}
</script>

<div class="container mx-auto space-y-6 p-4">
    <header
        class="bg-surface-50-900-token border-surface-500/10 flex flex-wrap items-center justify-between gap-4 rounded-xl border p-4 shadow-lg">
        <div class="flex items-center gap-3">
            <div class="bg-primary-500/10 rounded-lg p-2">
                <History size={24} class="text-primary-500" />
            </div>
            <div>
                <h1 class="h2 font-black tracking-tight">Activity Logs</h1>
                <p
                    class="text-xs font-bold tracking-widest uppercase opacity-50">
                    Audit Trail & History
                </p>
            </div>
        </div>
        <div class="flex gap-2">
            <button
                class="btn btn-sm preset-filled-primary font-bold shadow-lg"
                onclick={load_logs}
                disabled={loading}>
                {#if loading}
                    <RefreshCcw size={16} class="mr-2 animate-spin" /> Updating...
                {:else}
                    <RefreshCcw size={16} class="mr-2" /> Refresh Logs
                {/if}
            </button>
        </div>
    </header>

    <!-- Filter Bar -->
    <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 Keywords</span>
                <form
                    onsubmit={handle_search}
                    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="Action, name, description..." />
                    <button
                        type="submit"
                        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"
                        disabled={loading}>
                        <span class="tracking-wide whitespace-nowrap"
                            >Search</span>
                    </button>
                </form>
            </div>

            <div class="space-y-1">
                <span
                    class="label ml-1 block text-xs font-bold tracking-wider uppercase opacity-75"
                    >Display Limit</span>
                <select
                    class="select preset-filled-surface border-surface-500/20 rounded-lg border p-2 text-sm"
                    bind:value={limit}
                    onchange={load_logs}>
                    <option value={25}>Latest 25</option>
                    <option value={50}>Latest 50</option>
                    <option value={100}>Latest 100</option>
                    <option value={250}>Latest 250</option>
                </select>
            </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 log_li.length === 0}
        <div
            class="card preset-tonal-surface border-surface-500/20 rounded-2xl border-2 border-dashed p-12 text-center">
            <Activity size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Logs Found</h3>
            <p class="mx-auto mt-2 max-w-xs opacity-60">
                Try broadening your search or check another account.
            </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" />
                System Events
                <span class="badge preset-tonal-secondary ml-auto"
                    >{log_li.length} entries shown</span>
            </h3>

            <div class="table-container">
                <table class="table-hover table">
                    <thead>
                        <tr
                            class="text-[10px] tracking-widest uppercase opacity-60">
                            <th>Timestamp</th>
                            <th>Identity</th>
                            <th>Action</th>
                            <th>Resource</th>
                            <th>Summary</th>
                        </tr>
                    </thead>
                    <tbody>
                        {#each log_li as log, index (index)}
                            <tr class="text-sm transition-colors">
                                <!-- Date/Time -->
                                <td class="whitespace-nowrap">
                                    <div class="flex items-center gap-2">
                                        <Calendar
                                            size={14}
                                            class="opacity-40" />
                                        <div class="flex flex-col">
                                            <span class="font-bold"
                                                >{ae_util.iso_datetime_formatter(
                                                    log.created_on,
                                                    'date_short'
                                                )}</span>
                                            <span
                                                class="flex items-center gap-1 text-[10px] opacity-50">
                                                <Clock size={10} />
                                                {ae_util.iso_datetime_formatter(
                                                    log.created_on,
                                                    'time_12_short'
                                                )}
                                            </span>
                                        </div>
                                    </div>
                                </td>

                                <!-- User/Person -->
                                <td>
                                    <div class="flex items-center gap-2">
                                        <div
                                            class="avatar preset-tonal-surface flex h-8 w-8 items-center justify-center rounded-full shadow-inner">
                                            <User
                                                size={14}
                                                class="opacity-60" />
                                        </div>
                                        <div
                                            class="flex max-w-[180px] flex-col">
                                            {#if log.person_full_name || log.person_id_random}
                                                <span class="truncate font-bold"
                                                    >{log.person_full_name ||
                                                        'Person'}</span>
                                                <span
                                                    class="font-mono text-[9px] uppercase opacity-40"
                                                    >ID: {log.person_id_random ||
                                                        '--'}</span>
                                            {:else if log.name}
                                                <span class="italic opacity-70"
                                                    >{log.name}</span>
                                            {:else}
                                                <span class="italic opacity-30"
                                                    >Unknown</span>
                                            {/if}
                                        </div>
                                    </div>
                                </td>

                                <!-- Action -->
                                <td>
                                    <div class="flex flex-col gap-1">
                                        <span
                                            class="badge preset-filled-surface px-2 text-[9px] font-black tracking-tighter uppercase">
                                            {log.action}
                                        </span>
                                        {#if log.action_with}
                                            <span
                                                class="ml-1 flex items-center gap-1 text-[9px] font-bold uppercase opacity-40">
                                                <ShieldCheck size={8} /> via {log.action_with}
                                            </span>
                                        {/if}
                                    </div>
                                </td>

                                <!-- Context -->
                                <td>
                                    {#if log.object_type}
                                        <div
                                            class="border-surface-500/10 flex items-center gap-2 rounded-lg border bg-black/5 p-2">
                                            <Tag
                                                size={12}
                                                class="text-secondary-500 shrink-0" />
                                            <div
                                                class="flex flex-col truncate text-[10px]">
                                                <span
                                                    class="font-bold tracking-tighter uppercase"
                                                    >{log.object_type}</span>
                                                {#if log.external_client_id}
                                                    <span
                                                        class="truncate font-mono opacity-40"
                                                        >{log.external_client_id}</span>
                                                {/if}
                                            </div>
                                        </div>
                                    {:else}
                                        <span class="text-xs italic opacity-20"
                                            >--</span>
                                    {/if}
                                </td>

                                <!-- Summary/Description -->
                                <td>
                                    <div class="flex max-w-sm flex-col gap-1">
                                        {#if log.summary}
                                            <span
                                                class="text-primary-500 leading-tight font-bold"
                                                >{log.summary}</span>
                                        {/if}
                                        {#if log.description}
                                            <p
                                                class="line-clamp-2 text-xs italic opacity-60"
                                                title={log.description}>
                                                {log.description}
                                            </p>
                                        {/if}
                                        {#if !log.summary && !log.description}
                                            <span
                                                class="text-[10px] italic opacity-20"
                                                >No detail record</span>
                                        {/if}
                                    </div>
                                </td>
                            </tr>
                        {/each}
                    </tbody>
                </table>
            </div>
        </div>
    {/if}
</div>
