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

let log_lvl: number = $state(0);
// console.log(`ae_events_pres_mgmt event [slug] +page.svelte data:`, data);

import { page } from '$app/stores';
import { untrack } from 'svelte';

import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';

import { liveQuery } from 'dexie';
// import { core_func } from '$lib/ae_core_functions';
import { db_events } from '$lib/ae_events/db_events';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import {
    EVENTS_MODULE_TITLE,
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { pres_mgmt_loc } from '$lib/stores/ae_events_stores__pres_mgmt.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';

import Event_reports_page_menu from './event_reports_page_menu.svelte';
import Reports_sessions from './reports_sessions.svelte';
import Reports_presenters from './reports_presenters.svelte';
import Reports_files from './reports_files.svelte';
import Reports_file_downloads from './reports_file_downloads.svelte';
import {
    Check,
    ClipboardList,
    Download,
    File,
    IdCard,
    ListChecks,
    LoaderCircle,
    TrendingUp,
    X
} from '@lucide/svelte';
// import Comp_event_file_obj_tbl from '../../ae_comp__event_file_obj_tbl.svelte';

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
let ae_acct = $derived(data[data.account_id]);

$effect(() => {
    if (!ae_acct) return;
    untrack(() => {
        if (log_lvl) {
            console.log(`$slct.account_id = `, $slct.account_id);
            console.log(`ae_acct = `, ae_acct);
            console.log(`TEST $page.url.hash`, $page?.url?.hash);
        }

        $events_slct.event_id = ae_acct.slct.event_id;
        $events_slct.event_obj = ae_acct.slct.event_obj;
        $events_slct.event_session_obj_li = ae_acct.slct.event_session_obj_li;
    });
});

let lq__event_obj = $derived(
    liveQuery(async () => {
        let results = await db_events.event.get(ae_acct?.slct.event_id);
        return results;
    })
);

// Sync server-side pres_mgmt config into local PersistedState.
// WHY: this page can be reached directly without first visiting the pres_mgmt
// overview or a session page — the only other places this sync runs. Without
// it, pres_mgmt_loc.current keeps stale defaults for report display flags.
$effect(() => {
    const remote_cfg = $lq__event_obj?.mod_pres_mgmt_json;
    if (remote_cfg) {
        untrack(() => {
            events_func.sync_config__event_pres_mgmt({
                pres_mgmt_cfg_remote: remote_cfg,
                log_lvl: 0
            });
        });
    }
});

// It is important that these not be set to a value! It messes with the Dexie LiveQuery.
// let event_file_id_li: Array<string> = $state();
// let event_session_id_li: Array<string> = $state();
// let event_presentation_id_li: Array<string>;
// let event_presenter_id_li: Array<string> = $state();

// let load_obj_li_results: Promise<any>|key_val;
// let search_submit_results: Promise<any>|key_val;

// let ae_promises: key_val = $state({});
// let ae_tmp: key_val = {};
let ae_triggers: key_val = $state({
    rpt__event_files: true,
    rpt__event_sessions: true,
    rpt__event_presenters: true,
    rpt__file_downloads: true
});

let url_hash: string = $state($page?.url?.hash);

$effect(() => {
    if (url_hash) {
        url_hash = url_hash.replace('#', '');
        if (log_lvl) {
            console.log(`URL hash changed: ${url_hash}`);
        }
        pres_mgmt_loc.current.show_report = url_hash;
    }
});
</script>

<svelte:head>
    <title>
        Reports: {ae_util.shorten_string({
            string: $lq__event_obj?.name,
            max_length: 12
        })}
        ({$lq__event_obj?.event_id}) - Pres Mgmt - {EVENTS_MODULE_TITLE}
    </title>
</svelte:head>

<Event_reports_page_menu {lq__event_obj} />

{#if !$lq__event_obj}
    <div>
        <LoaderCircle size="1em" class="m-1 animate-spin" />
        <span>Loading event information...</span>
    </div>
{:else}
    <header class="ae_module_header">
        <!-- <span
        class="flex flex-row flex-wrap gap-1 items-center justify-center"
        > -->

        <!-- rounded-md p-1 px-2 -->
        <!-- preset-filled-surface-400-600 text-neutral-800/90 -->
        <h2
            class="
            h2 flex
            w-full flex-row items-center justify-between gap-0.25 text-center
            ">
            <span class="flex flex-row items-center gap-1">
                <TrendingUp size="1em" class="m-1 text-neutral-800/80" />
                Reports
            </span>
            <!-- Reports for: -->
            {#if $lq__event_obj?.cfg_json?.short_name}
                <!-- eslint-disable-next-line svelte/no-at-html-tags -->
                {@html $lq__event_obj?.cfg_json.short_name ??
                    ae_snip.html__not_set}
            {:else}
                <!-- eslint-disable-next-line svelte/no-at-html-tags -->
                {@html $lq__event_obj?.name ?? ae_snip.html__not_set}
            {/if}
        </h2>
    </header>

    <div
        class="preset-tonal-success border-success-500 my-2 flex flex-row flex-wrap items-center justify-center gap-1 rounded-md border p-2">
        <span class="rounded-md border border-gray-200 p-1">
            <!-- Sessions without files uploaded -->
            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_sessions = true;
                    pres_mgmt_loc.current.show_report = 'session_no_files';
                }}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                class:hidden={pres_mgmt_loc.current.hide__report_kv['session_no_files'] && !$ae_loc.edit_mode}
                title="Toggle to show sessions with and without files uploaded.">
                {#if pres_mgmt_loc.current.show_report == 'session_no_files' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else}
                    <ClipboardList size="1em" class="m-1" />
                {/if}
                Sessions
                {#if pres_mgmt_loc.current.rpt__session_no_files}
                    With
                {:else}
                    Without
                {/if}
                Files
            </button>

            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_sessions = true;
                    pres_mgmt_loc.current.show_report = 'sessions_poc_agree';
                }}
                class:hidden={!pres_mgmt_loc.current.require__session_agree}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Toggle to show POCs who have agreed to session terms and conditions.">
                {#if pres_mgmt_loc.current.show_report == 'sessions_poc_agree' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else if pres_mgmt_loc.current.rpt__session_poc_agree}
                    <Check size="1em" class="m-1" />
                {:else}
                    <X size="1em" class="m-1" />
                {/if}
                {#if pres_mgmt_loc.current.rpt__session_poc_agree}
                    Session {pres_mgmt_loc.current.label__session_poc_name}s
                    Agreed
                {:else}
                    Session {pres_mgmt_loc.current.label__session_poc_name}s
                    Not Agreed
                {/if}
            </button>

            <!-- Sessions without POC bios -->
            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_sessions = true;
                    pres_mgmt_loc.current.show_report = 'session_no_bio';
                }}
                class:hidden={(pres_mgmt_loc.current.hide__report_kv['session_no_bio'] && !$ae_loc.edit_mode)}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Show sessions without POC bios.">
                {#if pres_mgmt_loc.current.show_report == 'session_no_bio' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else}
                    <IdCard size="1em" class="m-1" />
                    <!-- <span class="fas fa-book m-1"></span> -->
                {/if}
                Session {pres_mgmt_loc.current.label__session_poc_name} Bios
            </button>
        </span>

        <span class="rounded-md border border-gray-200 p-1">
            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_presenters = true;
                    pres_mgmt_loc.current.show_report = 'presenters_agree';
                }}
                class:hidden={!pres_mgmt_loc.current.require__presenter_agree}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Show presenters who have agreed to present.">
                {#if pres_mgmt_loc.current.show_report == 'presenters_agree' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else if pres_mgmt_loc.current.rpt__presenter_agree}
                    <Check size="1em" class="m-1" />
                {:else}
                    <X size="1em" class="m-1" />
                {/if}
                Presenters
                {#if pres_mgmt_loc.current.rpt__presenter_agree}
                    Agreed
                {:else}
                    Not Agreed
                {/if}
            </button>

            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_presenters = true;
                    pres_mgmt_loc.current.show_report = 'presenters_biography';
                }}
                class:hidden={(pres_mgmt_loc.current.hide__report_kv['presenters_biography'] && !$ae_loc.edit_mode)}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Show presenters with bios.">
                {#if pres_mgmt_loc.current.show_report == 'presenters_biography' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else}
                    <IdCard size="1em" class="m-1" />
                    <!-- <span class="fas fa-book m-1"></span> -->
                {/if}
                Presenter Bios
            </button>

            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_presenters = true;
                    pres_mgmt_loc.current.show_report = 'presenters_overview';
                }}
                class:hidden={(pres_mgmt_loc.current.hide__report_kv['presenters_overview'] && !$ae_loc.edit_mode)}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Show overview of presenters' statuses. (A work in progress for LCI)">
                {#if pres_mgmt_loc.current.show_report == 'presenters_overview' && $events_sess.pres_mgmt?.status_qry__search == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else}
                    <ListChecks size="1em" class="m-1" />
                {/if}
                Overview of Presenters
            </button>
        </span>

        <span class="rounded-md border border-gray-200 p-1">
            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__event_files = true;
                    pres_mgmt_loc.current.show_report = 'event_files';
                }}
                class:hidden={(pres_mgmt_loc.current.hide__report_kv['event_files'] && !$ae_loc.edit_mode)}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="Show large file uploads.">
                {#if $events_sess.pres_mgmt?.show_report == 'event_files' && $events_sess.pres_mgmt.status_rpt[$events_sess.pres_mgmt?.show_report] == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {/if}
                <File size="1em" class="m-1" />
                Event Files
            </button>

            <button
                type="button"
                disabled={!$ae_loc.trusted_access}
                onclick={() => {
                    ae_triggers.rpt__file_downloads = true;
                    pres_mgmt_loc.current.show_report = 'file_downloads';
                }}
                class:hidden={(pres_mgmt_loc.current.hide__report_kv['file_downloads'] && !$ae_loc.edit_mode)}
                class="btn btn-sm preset-tonal-success border-success-500 hover:preset-filled-success-500 m-1 border transition-all"
                title="File Downloads — download files grouped by session and presenter with clean filename options.">
                {#if pres_mgmt_loc.current.show_report == 'file_downloads' && $events_sess.pres_mgmt.status_rpt.file_downloads == 'loading'}
                    <LoaderCircle size="1em" class="animate-spin" />
                {:else}
                    <Download size="1em" class="m-1" />
                {/if}
                File Downloads
            </button>
        </span>
    </div>

    <!-- All Event Session related reports -->
    {#if pres_mgmt_loc.current.show_report == 'session_no_files' || pres_mgmt_loc.current.show_report == 'session_no_bio' || pres_mgmt_loc.current.show_report == 'sessions_poc_agree'}
        <Reports_sessions
            {lq__event_obj}
            event_session_obj_li={$events_sess.event_session_obj_li}
            rpt__name={pres_mgmt_loc.current.show_report}
            rpt__sort={pres_mgmt_loc.current.qry__session_sort}
            rpt__enabled={pres_mgmt_loc.current.qry_enabled}
            rpt__hidden={pres_mgmt_loc.current.qry_hidden}
            rpt__limit={pres_mgmt_loc.current.qry_limit__sessions}
            bind:qry__status={$events_sess.pres_mgmt.status_qry__search}
            qry__count={$events_sess.event_session_obj_li?.length ?? 0}
            bind:qry__trigger={ae_triggers.rpt__event_sessions}
            hide_session_code={pres_mgmt_loc.current.hide__session_code}
            {log_lvl} />
    {/if}

    <!-- All Event Presenter related reports -->
    {#if pres_mgmt_loc.current.show_report == 'presenters_agree' || pres_mgmt_loc.current.show_report == 'presenters_biography' || pres_mgmt_loc.current.show_report == 'presenters_overview'}
        <Reports_presenters
            {lq__event_obj}
            event_presenter_obj_li={$events_sess.event_presenter_obj_li}
            rpt__name={pres_mgmt_loc.current.show_report}
            rpt__sort={pres_mgmt_loc.current.qry__presenter_sort}
            rpt__enabled={pres_mgmt_loc.current.qry_enabled}
            rpt__hidden={pres_mgmt_loc.current.qry_hidden}
            rpt__limit={pres_mgmt_loc.current.qry_limit__presenters}
            bind:qry__status={$events_sess.pres_mgmt.status_qry__search}
            qry__count={$events_sess.event_presenter_obj_li?.length ?? 0}
            bind:qry__trigger={ae_triggers.rpt__event_presenters}
            hide_session_code={pres_mgmt_loc.current.hide__session_code}
            {log_lvl} />
    {/if}

    <!-- All Event File related reports -->
    {#if pres_mgmt_loc.current.show_report == 'event_files' || pres_mgmt_loc.current.show_report == 'recent_files' || pres_mgmt_loc.current.show_report == 'large_files'}
        <Reports_files
            {lq__event_obj}
            event_file_obj_li={$events_sess.event_file_obj_li}
            rpt__name={pres_mgmt_loc.current.show_report}
            rpt__sort={pres_mgmt_loc.current.qry__files_sort}
            rpt__limit={pres_mgmt_loc.current.qry_limit__files}
            bind:qry__status={$events_sess.pres_mgmt.status_qry__search}
            qry__count={$events_sess.event_file_obj_li?.length ?? 0}
            bind:qry__trigger={ae_triggers.rpt__event_files}
            hide_session_code={pres_mgmt_loc.current.hide__session_code}
            {log_lvl} />
    {/if}

    <!-- File Downloads report — grouped by session/presenter with clean filename options -->
    {#if pres_mgmt_loc.current.show_report == 'file_downloads'}
        <Reports_file_downloads
            {lq__event_obj}
            rpt__limit={pres_mgmt_loc.current.qry_max}
            bind:qry__status={$events_sess.pres_mgmt.status_qry__search}
            bind:qry__trigger={ae_triggers.rpt__file_downloads}
            {log_lvl} />
    {/if}
{/if}
