<script lang="ts">
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
    log_lvl?: number;
}
let { data, log_lvl = 0 }: Props = $props();

import { liveQuery } from 'dexie';
import { page } from '$app/state';

import { ae_loc } from '$lib/stores/ae_stores';
import { db_events } from '$lib/ae_events/db_events';
import { EVENTS_MODULE_TITLE } from '$lib/stores/ae_events_stores';

import { ArrowLeft, TrendingUp, Type, Gauge, FileSpreadsheet, LoaderCircle } from '@lucide/svelte';
import Reports_badge_long_names from './reports_badge_long_names.svelte';
import Reports_badge_print_throughput from './reports_badge_print_throughput.svelte';
import Reports_badge_export from './reports_badge_export.svelte';

let event_id = $derived(page.params.event_id);

type ReportKey = 'long_names' | 'print_throughput' | 'export';
let active_report: ReportKey | null = $state(null);

let lq__event_obj = $derived(
    liveQuery(async () => {
        if (!event_id) return null;
        return db_events.event.get(event_id);
    })
);

let lq__badge_li = $derived(
    liveQuery(async () => {
        if (!event_id) return [];
        return db_events.badge.where('event_id').equals(event_id).toArray();
    })
);

let is_trusted = $derived($ae_loc?.trusted_access === true);
let badge_count = $derived($lq__badge_li?.length ?? 0);
let printed_count = $derived($lq__badge_li?.filter((b) => (b.print_count ?? 0) >= 1).length ?? 0);
let reprint_count = $derived(
    $lq__badge_li?.reduce((sum, b) => sum + Math.max(0, (b.print_count ?? 0) - 1), 0) ?? 0
);
</script>

<svelte:head>
    <title>
        Badge Reports — {$lq__event_obj?.name ?? '…'} — {EVENTS_MODULE_TITLE}
    </title>
</svelte:head>

{#if !is_trusted}
    <div class="card p-8 text-center">
        <p class="text-error-500 font-semibold">Trusted access required for badge reports.</p>
    </div>
{:else}
    <header class="mb-3 flex w-full flex-row flex-wrap items-center justify-between gap-2 border-b border-surface-300 dark:border-surface-700 pb-2">
        <div class="flex flex-row items-center gap-2">
            <a
                href={`/events/${event_id}/badges`}
                class="btn btn-sm preset-tonal-surface border border-surface-300-700 flex items-center gap-1">
                <ArrowLeft size="1em" />
                <span class="hidden sm:inline">Badges</span>
            </a>
            <div class="flex flex-col">
                <h2 class="flex items-center gap-1 text-base font-bold">
                    <TrendingUp size="1em" class="shrink-0 text-primary-500" />
                    Badge Reports
                </h2>
                {#if $lq__event_obj?.name}
                    <p class="text-sm text-surface-600-400">{$lq__event_obj.name}</p>
                {/if}
            </div>
        </div>
        <div class="text-sm text-surface-600-400">
            {badge_count} badges · {printed_count} printed{reprint_count > 0 ? ` (${reprint_count} reprint${reprint_count !== 1 ? 's' : ''})` : ''}
        </div>
    </header>

    <!-- Report selector — styled like pres_mgmt reports for visual consistency -->
    <div class="preset-tonal-primary border-primary-300 dark:border-primary-700 my-2 flex flex-row flex-wrap items-center gap-2 rounded-md border p-2">
        <span class="text-xs font-semibold uppercase tracking-wide text-primary-700 dark:text-primary-300 pr-1">
            Reports:
        </span>
        <button
            type="button"
            onclick={() => (active_report = 'long_names')}
            class="btn btn-sm border transition-all"
            class:preset-filled-primary={active_report === 'long_names'}
            class:border-primary-600={active_report === 'long_names'}
            class:preset-tonal-primary={active_report !== 'long_names'}
            class:border-primary-400={active_report !== 'long_names'}
            title="List badges with the longest given, family, or full names">
            <Type size="1em" />
            Long Names
        </button>
        <button
            type="button"
            onclick={() => (active_report = 'print_throughput')}
            class="btn btn-sm border transition-all"
            class:preset-filled-primary={active_report === 'print_throughput'}
            class:border-primary-600={active_report === 'print_throughput'}
            class:preset-tonal-primary={active_report !== 'print_throughput'}
            class:border-primary-400={active_report !== 'print_throughput'}
            title="Show number of badges printed per time window">
            <Gauge size="1em" />
            Print Throughput
        </button>
        <button
            type="button"
            onclick={() => (active_report = 'export')}
            class="btn btn-sm border transition-all"
            class:preset-filled-primary={active_report === 'export'}
            class:border-primary-600={active_report === 'export'}
            class:preset-tonal-primary={active_report !== 'export'}
            class:border-primary-400={active_report !== 'export'}
            title="Export badge data to CSV for post-event reporting">
            <FileSpreadsheet size="1em" />
            Export CSV
        </button>
    </div>

    {#if $lq__badge_li === undefined}
        <div class="flex items-center gap-2 py-8 opacity-50">
            <LoaderCircle size="1.5em" class="animate-spin" />
            <span>Loading badge data…</span>
        </div>
    {:else if active_report === 'long_names'}
        <Reports_badge_long_names badge_li={$lq__badge_li} event_id={event_id ?? ''} {log_lvl} />
    {:else if active_report === 'print_throughput'}
        <Reports_badge_print_throughput badge_li={$lq__badge_li} event_id={event_id ?? ''} {log_lvl} />
    {:else if active_report === 'export'}
        <Reports_badge_export
            badge_li={$lq__badge_li}
            event_id={event_id ?? ''}
            event_name={$lq__event_obj?.name ?? ''}
            {log_lvl} />
    {:else}
        <p class="py-4 text-sm text-surface-600-400">Select a report above to view results.</p>
    {/if}
{/if}
