<script lang="ts">
import { untrack } from 'svelte';
import { slide } from 'svelte/transition';
interface Props {
    /** @type {import('./$types').PageData} */
    data: any;
    log_lvl?: number;
}

let { data, log_lvl = $bindable(1) }: Props = $props();

// *** Import Svelte specific

// *** Import other supporting libraries
import { liveQuery } from 'dexie';

// *** Import Aether specific variables and functions
import { ae_util } from '$lib/ae_utils/ae_utils';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { page } from '$app/state';

import { db_events } from '$lib/ae_events/db_events';
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { badges_loc } from '$lib/stores/ae_events_stores__badges.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';

import Comp_badge_search from './ae_comp__badge_search.svelte';
import Comp_badge_obj_li from './ae_comp__badge_obj_li.svelte';
import Comp_badge_create_form from './ae_comp__badge_create_form.svelte';
import Comp_badge_upload_form from './ae_comp__badge_upload_form.svelte';

import { UserPlus, Printer, Upload, FileText, ChartColumnBig, LayoutTemplate, TrendingUp } from '@lucide/svelte';

// Sync events_slct.event_id from the URL param so direct navigation works.
// Without this, events_slct.event_id relies on ae_acct.slct.event_id (set by the
// events list) and is null if the user navigated directly to this URL.
$effect(() => {
    const url_event_id = page.params.event_id;
    if (url_event_id) {
        untrack(() => { $events_slct.event_id = url_event_id; });
    }
});

// Load templates for this event so the create form can show the selector and
// derive badge_type_code_li from whichever template the user picks.
$effect(() => {
    const event_id = $events_slct?.event_id;
    if (!event_id) return;
    events_func.load_ae_obj_li__event_badge_template({
        api_cfg: $ae_api,
        event_id,
        log_lvl: 0
    });
});

let lq__badge_template_li = $derived(
    liveQuery(async () => {
        const event_id = $events_slct?.event_id;
        if (!event_id) return [];
        return await db_events.badge_template
            .where('event_id')
            .equals(event_id)
            .sortBy('name');
    })
);
// badges_loc (PersistedState) is always initialized from badges_loc_defaults —
// no manual typeof guards needed. All fields are guaranteed to exist.

// Variables
let show_create_badge_modal: boolean = $state(false);
let show_upload_badge_modal: boolean = $state(false);
let create_badge_dialog: HTMLDialogElement | undefined = $state();
let upload_badge_dialog: HTMLDialogElement | undefined = $state();

let event_badge_id_li: Array<string> = $state([]);
let search_debounce_timer: any = null;
let last_search_id = 0;
let last_executed_key = ''; // Search Guard Key

let lq__event_obj = $derived(
    liveQuery(async () => {
        if (log_lvl) {
            console.log(
                `*** LiveQuery: lq__event_obj *** event_id=${$events_slct.event_id}`
            );
        }
        let results = await db_events.event.get($events_slct?.event_id ?? '');

        return results;
    })
);

// Mirror server-side badges config into the persisted local store when the
// event object is available so UI can read a fast local copy.
$effect(() => {
    const remote_cfg = $lq__event_obj?.mod_badges_json;
    if (remote_cfg) {
        untrack(() => {
            events_func.sync_config__event_badges({
                badges_cfg_remote: remote_cfg,
                log_lvl: log_lvl
            });
        });
    }
});

// Stable LiveQuery Pattern (Aether UI V3)
let lq__event_badge_obj_li = $derived.by(() => {
    const ids = event_badge_id_li;
    const event_id = $events_slct?.event_id;
    // Read in outer scope so Svelte tracks it — liveQuery async callbacks are not tracked.
    // In edit mode the stepper controls the limit; otherwise fall back to 50.
    const fallback_limit = $ae_loc.edit_mode ? badges_loc.current.qry_result_limit : 50;

    return liveQuery(async () => {
        // SCENARIO 1: Specific IDs provided (Search Results)
        if (Array.isArray(ids) && ids.length > 0) {
            if (log_lvl)
                console.log(`Badge Page LQ: bulkGet ${ids.length} IDs`);
            const results = await db_events.badge.bulkGet(ids);
            return results.filter((item) => item !== undefined);
        }

        // SCENARIO 2: Fallback broad search (Only if no active filters)
        // Unauthenticated users must enter a query — never show the full attendee list.
        if (
            event_id &&
            $ae_loc.trusted_access &&
            !badges_loc.current.fulltext_search_qry_str &&
            badges_loc.current.qry_printed_status === 'all' &&
            !badges_loc.current.qry_affiliations &&
            !badges_loc.current.search_badge_type_code
        ) {
            if (log_lvl)
                console.log(
                    `Badge Page LQ: Fallback search for event: ${event_id}`
                );
            // Dexie sortBy supports only one field; sort by print_count then name in JS.
            const fallback_results = await db_events.badge
                .where('event_id')
                .equals(event_id)
                .limit(fallback_limit)
                .toArray();
            fallback_results.sort((a, b) =>
                (a.print_count ?? 0) - (b.print_count ?? 0) ||
                (a.given_name ?? '').localeCompare(b.given_name ?? '')
            );
            return fallback_results;
        }

        return [];
    });
});

// Standardized Reactive Search Pattern (Aether UI V3)
// 1. Isolate dependencies into a stable derived object
// Resolve per-tier search constraints from the event config (mirrored from mod_badges_json).
// Tier order (highest wins): trusted_access → auth (public/authenticated) → anonymous.
let effective_search_limits = $derived.by(() => {
    if ($ae_loc.trusted_access) {
        return {
            result_limit: badges_loc.current.trusted_search_result_limit,
            min_chars: badges_loc.current.trusted_search_min_chars
        };
    }
    if ($ae_loc.authenticated_access) {
        // public_access / authenticated — signed in but below trusted
        return {
            result_limit: badges_loc.current.auth_search_result_limit,
            min_chars: badges_loc.current.auth_search_min_chars
        };
    }
    return {
        result_limit: badges_loc.current.anon_search_result_limit,
        min_chars: badges_loc.current.anon_search_min_chars
    };
});

let search_params = $derived({
    v: badges_loc.current.search_version,
    str: (badges_loc.current.fulltext_search_qry_str ?? '')
        .toLowerCase()
        .trim(),
    type: badges_loc.current.search_badge_type_code,
    printed: badges_loc.current.qry_printed_status,
    aff: (badges_loc.current.qry_affiliations ?? '').toLowerCase().trim(),
    sort: badges_loc.current.qry_sort_order,
    visibility_filter: badges_loc.current.visibility_filter,
    event_id: $events_slct?.event_id,
    remote_first: badges_loc.current.qry__remote_first,
    // In edit mode the stepper overrides the server-configured tier limit.
    result_limit: $ae_loc.edit_mode
        ? badges_loc.current.qry_result_limit
        : effective_search_limits.result_limit,
    min_chars: effective_search_limits.min_chars
});

// 2. Controlled effect for triggering searches
$effect(() => {
    const params = search_params;

    if (search_debounce_timer) clearTimeout(search_debounce_timer);
    search_debounce_timer = setTimeout(() => {
        untrack(() => {
            handle_search_refresh(params);
        });
    }, 300);

    return () => {
        if (search_debounce_timer) clearTimeout(search_debounce_timer);
    };
});

async function handle_search_refresh(params: any) {
    // 1. Guard
    const qry_key = JSON.stringify(params);
    if (qry_key === last_executed_key) return;
    last_executed_key = qry_key;

    const current_search_id = ++last_search_id;
    const event_id = params.event_id;
    const remote_first = params.remote_first;

    if (log_lvl)
        console.log(
            `[Badge Search #${current_search_id}] Refreshing (remote=${remote_first}, event=${event_id}, str=${params.str})...`
        );

    untrack(() => {
        $events_sess.badges.search_status = 'loading';
        $events_sess.badges.search_complete = false;
    });

    const qry_str = params.str;
    const type_code = params.type;
    const printed_status = params.printed;
    const aff_str = params.aff;
    const result_limit = params.result_limit;
    const min_chars = params.min_chars;

    const visibility_filter = params.visibility_filter as 'default' | 'show_hidden' | 'show_all';
    const show_hidden = visibility_filter !== 'default';
    const show_all = visibility_filter === 'show_all';

    // Defense-in-depth: enforce min_chars even if the search component lets one through.
    // Exception: if the user has set a non-default filter or sort, that is explicit intent —
    // run the search even without a text query.
    const has_active_filters =
        printed_status !== 'all' || !!type_code || !!aff_str || !!params.sort || show_hidden;
    if (qry_str.length < min_chars && !has_active_filters) {
        untrack(() => {
            event_badge_id_li = [];
            $events_sess.badges.search_status = 'done';
            $events_sess.badges.search_complete = true;
        });
        return;
    }

    // 2. FAST PATH: Local IDB Search
    if (!remote_first) {
        try {
            if (event_id) {
                let local_results = await db_events.badge
                    .where('event_id')
                    .equals(event_id)
                    .filter((badge) => {
                        // Exclude hidden/disabled badges unless the visibility filter allows them
                        if (!show_hidden && badge.hide) return false;
                        if (!show_all && badge.enable === false) return false;

                        if (type_code && badge.badge_type_code !== type_code)
                            return false;

                        if (printed_status !== 'all') {
                            const is_printed = (badge.print_count ?? 0) > 0;
                            if (printed_status === 'printed' && !is_printed)
                                return false;
                            if (printed_status === 'not_printed' && is_printed)
                                return false;
                        }

                        if (qry_str) {
                            const given_name = (
                                badge.given_name ?? ''
                            ).toLowerCase();
                            const family_name = (
                                badge.family_name ?? ''
                            ).toLowerCase();
                            const full_name =
                                `${given_name} ${family_name}`.toLowerCase();
                            const email = (badge.email ?? '').toLowerCase();
                            const qry_string = (
                                badge.default_qry_str ?? ''
                            ).toLowerCase();

                            const match =
                                full_name.includes(qry_str) ||
                                given_name.includes(qry_str) ||
                                family_name.includes(qry_str) ||
                                email.includes(qry_str) ||
                                qry_string.includes(qry_str);

                            if (!match) return false;
                        }

                        if (aff_str) {
                            const affiliations = (
                                badge.affiliations ?? ''
                            ).toLowerCase();
                            if (!affiliations.includes(aff_str)) return false;
                        }

                        return true;
                    })
                    .toArray();

                // Complex Sort Logic
                local_results.sort((a, b) => {
                    switch (params.sort) {
                        case 'name_asc':
                            return (
                                (a.given_name ?? '').localeCompare(
                                    b.given_name ?? ''
                                ) ||
                                (a.family_name ?? '').localeCompare(
                                    b.family_name ?? ''
                                )
                            );
                        case 'name_desc':
                            return (
                                (b.given_name ?? '').localeCompare(
                                    a.given_name ?? ''
                                ) ||
                                (b.family_name ?? '').localeCompare(
                                    a.family_name ?? ''
                                )
                            );
                        case 'updated_desc':
                            return (
                                new Date(b.updated_on || 0).getTime() -
                                new Date(a.updated_on || 0).getTime()
                            );
                        case 'updated_asc':
                            return (
                                new Date(a.updated_on || 0).getTime() -
                                new Date(b.updated_on || 0).getTime()
                            );
                        case 'print_count_desc':
                            return (b.print_count ?? 0) - (a.print_count ?? 0);
                        case 'print_first_desc':
                            return (
                                new Date(b.print_first_datetime || 0).getTime() -
                                new Date(a.print_first_datetime || 0).getTime()
                            );
                        case 'print_last_desc':
                            return (
                                new Date(b.print_last_datetime || 0).getTime() -
                                new Date(a.print_last_datetime || 0).getTime()
                            );
                        case 'badge_type_asc':
                            return (a.badge_type_code ?? '').localeCompare(
                                b.badge_type_code ?? ''
                            );
                        case 'affiliations_asc':
                            return (
                                (a.affiliations_override ?? a.affiliations ?? '').localeCompare(
                                    b.affiliations_override ?? b.affiliations ?? ''
                                )
                            );
                        default:
                            // Matches the API default: unprinted first, then alphabetical.
                            return (
                                (a.print_count ?? 0) - (b.print_count ?? 0) ||
                                (a.given_name ?? '').localeCompare(b.given_name ?? '')
                            );
                    }
                });

                // Cap results to the effective per-tier limit.
                local_results = local_results.slice(0, result_limit);

                const local_ids = local_results
                    .map((b) => b.event_badge_id)
                    .filter(Boolean);

                if (current_search_id === last_search_id) {
                    if (log_lvl)
                        console.log(
                            `[Badge Search #${current_search_id}] Fast Path found ${local_ids.length} items locally.`
                        );
                    untrack(() => {
                        event_badge_id_li = local_ids;
                        if (local_ids.length > 0)
                            $events_sess.badges.search_status = 'done';
                    });
                }
            }
        } catch (e) {
            if (log_lvl) console.warn('Badge Fast Path failed.', e);
        }
    } else {
        untrack(() => {
            event_badge_id_li = [];
        });
    }

    // 3. REVALIDATE: API Request
    try {
        // Map sort param to API order_by_li
        let order_by_li: any = {};
        switch (params.sort) {
            case 'name_asc':
                order_by_li = { given_name: 'ASC', family_name: 'ASC' };
                break;
            case 'name_desc':
                order_by_li = { given_name: 'DESC', family_name: 'DESC' };
                break;
            case 'updated_desc':
                order_by_li = { updated_on: 'DESC' };
                break;
            case 'updated_asc':
                order_by_li = { updated_on: 'ASC' };
                break;
            case 'print_count_desc':
                order_by_li = { print_count: 'DESC' };
                break;
            case 'print_first_desc':
                order_by_li = { print_first_datetime: 'DESC' };
                break;
            case 'print_last_desc':
                order_by_li = { print_last_datetime: 'DESC' };
                break;
            case 'badge_type_asc':
                order_by_li = { badge_type_code: 'ASC' };
                break;
            case 'affiliations_asc':
                order_by_li = { affiliations: 'ASC' };
                break;
            default:
                // Unprinted (print_count=0) first, then alphabetical within each group.
                order_by_li = { print_count: 'ASC', given_name: 'ASC' };
        }

        const results = await events_func.search__event_badge({
            api_cfg: $ae_api,
            event_id: event_id,
            fulltext_search_qry_str: qry_str || null,
            type_code: type_code || null,
            printed_status: printed_status,
            affiliations_qry_str: aff_str || null,
            enabled: show_all ? 'all' : 'enabled',
            hidden: show_hidden ? 'all' : 'not_hidden',
            order_by_li: order_by_li,
            limit: result_limit,
            log_lvl: 0
        });

        if (current_search_id === last_search_id) {
            const api_results = results || [];
            const api_ids = api_results
                .map((b: any) => b.event_badge_id)
                .filter(Boolean);

            untrack(() => {
                $events_sess.badge_li = api_results;
                event_badge_id_li = api_ids;
                $events_sess.badges.search_status = 'done';
                $events_sess.badges.search_complete = true;
            });
            if (log_lvl)
                console.log(
                    `[Badge Search #${current_search_id}] Revalidation Complete. Found ${api_ids.length} items.`
                );
        }
    } catch (error) {
        if (current_search_id === last_search_id) {
            console.error('Badge revalidation failed:', error);
            untrack(() => {
                $events_sess.badges.search_status = 'error';
                $events_sess.badges.search_complete = true;
            });
        }
    }
}
</script>

<svelte:head>
    <title>
        &AElig;: Badges -
        {ae_util.shorten_string({
            string: $lq__event_obj?.name ?? '-- not set --',
            max_length: 12
        })}
        - OSIT's &AElig; Events
    </title>
</svelte:head>

<Comp_badge_search event_id={$events_slct?.event_id ?? ''} log_lvl={1}
></Comp_badge_search>

{#if $ae_loc.trusted_access && $ae_loc.edit_mode}
    <div transition:slide={{ duration: 200 }} class="flex flex-row gap-1 items-center justify-center">
    {#if $ae_loc.manager_access}
        <a
            href="/events/{$events_slct?.event_id}/templates"
            class="btn btn-sm preset-tonal-surface border-surface-300-700 border">
            <LayoutTemplate size="1em" />
            Templates
        </a>
    {/if}
    <a
        href={`/events/${$events_slct?.event_id}/badges/reports`}
        class="btn btn-sm preset-tonal-surface border-surface-300-700 border">
        <TrendingUp size="1em" />
        Reports
    </a>

    {#if badges_loc.current.enable_add_badge_btn ?? true}
        <button
            type="button"
            class="btn btn-sm preset-tonal-warning border-warning-500 border"
            onclick={() => {
                show_create_badge_modal = true;
                create_badge_dialog?.showModal();
            }}
            title="Manually create a badge for an attendee. Required fields: given name, family name, and email. Optional fields: badge type, affiliations, and any other custom fields defined in your event's badge templates."
            >
            <UserPlus size="1em" />
            Create Badge
        </button>
    {/if}

    {#if badges_loc.current.enable_upload_badge_li_btn ?? true}
        <button
            type="button"
            class="btn btn-sm preset-tonal-warning border-warning-500 border"
            onclick={() => {
                show_upload_badge_modal = true;
                upload_badge_dialog?.showModal();
            }}
            title="Upload a CSV file to bulk create badges. Required columns: given_name, family_name, email. Optional columns: badge_type_code, affiliations, and any other custom fields defined in your event's badge templates."
            >
            <Upload size="1em" /> Upload Badge List
        </button>
    {/if}
    </div>

    {#if badges_loc.current.enable_mass_print ?? true}
        <div class="flex flex-row gap-1 items-center justify-center">
            <a
                href={`/events/${$events_slct?.event_id}/badges/print_list?printed_status=not_printed`}
                class="btn preset-filled-secondary">
                <Printer size="1em" /> Print Unprinted
            </a>
            <a
                href={`/events/${$events_slct?.event_id}/badges/print_list`}
                class="btn preset-filled-secondary">
                <Printer size="1em" /> Print All
            </a>
            <a
                href={`/events/${$events_slct?.event_id}/templates`}
                class="btn btn-tertiary">
                <FileText size="1em" /> Manage Templates
            </a>
            <a
                href={`/events/${$events_slct?.event_id}/badges/stats`}
                class="btn btn-tertiary">
                <ChartColumnBig size="1em" /> Badge Printing Stats
            </a>
        </div>
    {/if}
{/if}



<!-- Create Badge modal — native <dialog> for focus trap + backdrop.
     Clicking the backdrop closes it. The form remounts each open so state is fresh. -->
<dialog
    bind:this={create_badge_dialog}
    class="w-full max-w-lg rounded-xl border border-gray-200 bg-white p-0 shadow-2xl dark:border-gray-700 dark:bg-gray-900"
    onclick={(e) => { if (e.target === create_badge_dialog) { create_badge_dialog?.close(); show_create_badge_modal = false; } }}
    onclose={() => { show_create_badge_modal = false; }}>
    <div class="border-surface-200-800 border-b px-5 py-3">
        <h2 class="text-surface-900-50 text-base font-semibold">Create Badge</h2>
    </div>
    {#if show_create_badge_modal}
        <Comp_badge_create_form
            event_id={$events_slct?.event_id ?? ''}
            template_li={$lq__badge_template_li ?? []}
            onsuccess={() => {
                create_badge_dialog?.close();
                show_create_badge_modal = false;
                // Trigger a remote-first refresh so the new badge appears in results
                badges_loc.current.search_version = (badges_loc.current.search_version ?? 0) + 1;
                badges_loc.current.qry__remote_first = true;
            }}
            oncancel={() => {
                create_badge_dialog?.close();
                show_create_badge_modal = false;
            }} />
    {/if}
</dialog>

<!-- Upload Badge List modal -->
<dialog
    bind:this={upload_badge_dialog}
    class="w-full max-w-lg rounded-xl border border-gray-200 bg-white p-0 shadow-2xl dark:border-gray-700 dark:bg-gray-900"
    onclick={(e) => {
        if (e.target === upload_badge_dialog) {
            upload_badge_dialog?.close();
            show_upload_badge_modal = false;
        }
    }}
    onclose={() => {
        show_upload_badge_modal = false;
    }}>
    <div class="border-surface-200-800 border-b px-5 py-3">
        <h2 class="text-surface-900-50 text-base font-semibold">Upload Badge List</h2>
    </div>
    {#if show_upload_badge_modal}
        <Comp_badge_upload_form
            event_id={$events_slct?.event_id ?? ''}
            onsuccess={() => {
                upload_badge_dialog?.close();
                show_upload_badge_modal = false;
                badges_loc.current.search_version = (badges_loc.current.search_version ?? 0) + 1;
                badges_loc.current.qry__remote_first = true;
            }}
            oncancel={() => {
                upload_badge_dialog?.close();
                show_upload_badge_modal = false;
            }} />
    {/if}
</dialog>

<Comp_badge_obj_li
    {lq__event_badge_obj_li}
    search_status={$events_sess?.badges?.search_status ?? null}
    log_lvl={1} />

<style>
dialog {
    margin: auto;
}
dialog::backdrop {
    background: rgb(0 0 0 / 0.55);
    backdrop-filter: blur(3px);
}
</style>
