<script lang="ts">
import { untrack } from 'svelte';
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 { db_events } from '$lib/ae_events/db_events';
import {
    events_loc,
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
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 { LoaderCircle, UserPlus } from '@lucide/svelte';

// 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');
    })
);
// *** Initialization & Store Guard ***
// Ensure all search fields are initialized to prevent circular undefined triggers
if ($events_loc.badges) {
    if (typeof $events_loc.badges.search_version === 'undefined')
        $events_loc.badges.search_version = 0;
    if (typeof $events_loc.badges.qry__remote_first === 'undefined')
        $events_loc.badges.qry__remote_first = false;
    if (typeof $events_loc.badges.fulltext_search_qry_str === 'undefined')
        $events_loc.badges.fulltext_search_qry_str = '';
    if (typeof $events_loc.badges.search_badge_type_code === 'undefined')
        $events_loc.badges.search_badge_type_code = '';
    if (typeof $events_loc.badges.qry_printed_status === 'undefined')
        $events_loc.badges.qry_printed_status = 'all';
    if (typeof $events_loc.badges.qry_affiliations === 'undefined')
        $events_loc.badges.qry_affiliations = '';
    if (typeof $events_loc.badges.qry_sort_order === 'undefined')
        $events_loc.badges.qry_sort_order = '';
}

// 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 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;
    })
);

// 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;

    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)
        if (
            event_id &&
            !$events_loc.badges.fulltext_search_qry_str &&
            $events_loc.badges.qry_printed_status === 'all' &&
            !$events_loc.badges.qry_affiliations &&
            !$events_loc.badges.search_badge_type_code
        ) {
            if (log_lvl)
                console.log(
                    `Badge Page LQ: Fallback search for event: ${event_id}`
                );
            return await db_events.badge
                .where('event_id')
                .equals(event_id)
                .limit(50)
                .sortBy('given_name');
        }

        return [];
    });
});

// Standardized Reactive Search Pattern (Aether UI V3)
// 1. Isolate dependencies into a stable derived object
let search_params = $derived({
    v: $events_loc.badges.search_version,
    str: ($events_loc.badges.fulltext_search_qry_str ?? '')
        .toLowerCase()
        .trim(),
    type: $events_loc.badges.search_badge_type_code,
    printed: $events_loc.badges.qry_printed_status,
    aff: ($events_loc.badges.qry_affiliations ?? '').toLowerCase().trim(),
    sort: $events_loc.badges.qry_sort_order,
    event_id: $events_slct?.event_id,
    remote_first: $events_loc.badges.qry__remote_first
});

// 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;

    // 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) => {
                        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);
                        default:
                            return (a.given_name ?? '').localeCompare(
                                b.given_name ?? ''
                            );
                    }
                });

                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;
            default:
                order_by_li = { 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,
            order_by_li: order_by_li,
            limit: 150,
            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.edit_mode}
    <div class="flex justify-end px-4">
        <button
            type="button"
            class="btn btn-sm preset-tonal-primary border-primary-500 border"
            onclick={() => {
                show_create_badge_modal = true;
                create_badge_dialog?.showModal();
            }}>
            <UserPlus size="1em" />
            Create Badge
        </button>
    </div>
{/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
                $events_loc.badges.search_version = ($events_loc.badges.search_version ?? 0) + 1;
                $events_loc.badges.qry__remote_first = true;
            }}
            oncancel={() => {
                create_badge_dialog?.close();
                show_create_badge_modal = false;
            }} />
    {/if}
</dialog>

{#if $events_sess?.badges?.search_status === 'loading' && event_badge_id_li.length === 0}
    <div
        class="flex flex-col items-center justify-center p-10 text-center opacity-50">
        <LoaderCircle size="3em" class="mx-auto mb-4 animate-spin" />
        <p class="text-xl">Loading badges...</p>
    </div>
{:else}
    <Comp_badge_obj_li {lq__event_badge_obj_li} log_lvl={1}></Comp_badge_obj_li>
{/if}

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