<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 { Search, History, Calendar, User, Tag, Activity, ListFilter, RefreshCcw, Clock, ShieldCheck } 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 p-4 space-y-6">
    <header class="flex flex-wrap justify-between items-center bg-surface-50-900-token p-4 rounded-xl shadow-lg border border-surface-500/10 gap-4">
        <div class="flex items-center gap-3">
            <div class="p-2 bg-primary-500/10 rounded-lg">
                <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 opacity-50 uppercase tracking-widest">Audit Trail & History</p>
            </div>
        </div>
        <div class="flex gap-2">
            <button class="btn btn-sm variant-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 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 Keywords</span>
                <form onsubmit={handle_search} 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="Action, name, description..." 
                    />
                    <button type="submit" 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]" disabled={loading}>
                        <span class="whitespace-nowrap tracking-wide">Search</span>
                    </button>
                </form>
            </div>

            <div class="space-y-1">
                <span class="label block text-xs font-bold opacity-75 uppercase tracking-wider ml-1">Display Limit</span>
                <select class="select variant-filled-surface rounded-lg text-sm border border-surface-500/20 p-2" 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 p-8 flex justify-center items-center h-64">
            <div class="placeholder animate-pulse w-full h-full rounded-2xl"></div>
        </div>
    {:else if log_li.length === 0}
        <div class="card p-12 text-center variant-glass-surface border-2 border-dashed border-surface-500/20 rounded-2xl">
            <Activity size={48} class="mx-auto mb-4 opacity-20" />
            <h3 class="h3 font-bold opacity-50">No Logs Found</h3>
            <p class="opacity-60 max-w-xs mx-auto mt-2">Try broadening your search or check another account.</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" />
                System Events
                <span class="badge variant-soft-secondary ml-auto">{log_li.length} entries shown</span>
            </h3>

            <div class="table-container">
                <table class="table table-hover">
                    <thead>
                        <tr class="uppercase text-[10px] tracking-widest 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}
                            <tr class="transition-colors text-sm">
                                <!-- 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="text-[10px] opacity-50 flex items-center gap-1">
                                                <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 variant-soft-surface w-8 h-8 flex items-center justify-center rounded-full shadow-inner">
                                            <User size={14} class="opacity-60" />
                                        </div>
                                        <div class="flex flex-col max-w-[180px]">
                                            {#if log.person_full_name || log.person_id_random}
                                                <span class="font-bold truncate">{log.person_full_name || 'Person'}</span>
                                                <span class="text-[9px] opacity-40 font-mono uppercase">ID: {log.person_id_random || '--'}</span>
                                            {:else if log.name}
                                                <span class="italic opacity-70">{log.name}</span>
                                            {:else}
                                                <span class="opacity-30 italic">Unknown</span>
                                            {/if}
                                        </div>
                                    </div>
                                </td>

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

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

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