<script lang="ts">
interface Props {
    event_id: string;
    log_lvl?: number;
}

let { event_id, log_lvl = 0 }: Props = $props();

// *** Import other supporting libraries
import {
    // Library,
    LoaderCircle,
    Minus,
    Plus,
    QrCode,
    RemoveFormatting,
    Search,
    StepForward,
    TriangleAlert
} from '@lucide/svelte';
import { fade, slide } from 'svelte/transition';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { events_sess } from '$lib/stores/ae_events_stores';
import { badges_loc } from '$lib/stores/ae_events_stores__badges.svelte';
import Element_qr_scanner from '$lib/elements/element_qr_scanner.svelte';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { liveQuery } from 'dexie';
// import { db_events } from '$lib/ae_events/db_events';

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

// Axonius 2026 badge type codes
// TODO: drive this from the event's badge templates so it's event-agnostic
let badge_type_code_li = [
    { code: 'attendee', name: 'In-Person Attendee' },
    { code: 'sponsor', name: 'Adapt26 Sponsor' },
    { code: 'test', name: 'Test' },
    { code: 'staff', name: 'Staff' },
    { code: 'guest', name: 'Guest' },
    { code: 'volunteer', name: 'Volunteer' },
    { code: 'member', name: 'Member' },
    { code: 'nonmember', name: 'Non-Member' },
];

// Steps of 25 up to 250, then 300/400/500 for trusted, then 100s up to 2500 for managers.
let limit_steps = $derived.by(() => {
    const small = Array.from({ length: 10 }, (_, i) => (i + 1) * 25); // 25…250
    const medium = [300, 400, 500]; // trusted max
    const large = Array.from({ length: 20 }, (_, i) => 600 + i * 100); // 600…2500
    if ($ae_loc.manager_access) return [...small, ...medium, ...large];
    if ($ae_loc.trusted_access) return [...small, ...medium];
    return [25];
});
let limit_idx = $derived.by(() => {
    const idx = limit_steps.indexOf(badges_loc.current.qry_result_limit);
    return idx >= 0 ? idx : 0;
});

// Resolve the minimum characters required for the current user's access tier.
// Mirrors the 3-tier logic in +page.svelte so both enforce the same threshold.
let effective_min_chars = $derived.by(() => {
    if ($ae_loc.trusted_access) return badges_loc.current.trusted_search_min_chars;
    if ($ae_loc.authenticated_access) return badges_loc.current.auth_search_min_chars;
    return badges_loc.current.anon_search_min_chars;
});

function handle_search_trigger() {
    const qry = (badges_loc.current.fulltext_search_qry_str ?? '').trim();
    if (qry.length < effective_min_chars) {
        document.getElementById('badge_fulltext_search_qry_str')?.focus();
        return;
    }
    badges_loc.current.search_version++;
}

let show_remote_first_confirm = $state(false);

function handle_remote_first_click(e: MouseEvent) {
    const checkbox = e.currentTarget as HTMLInputElement;
    if (checkbox.checked) {
        // User is enabling — hold the checkbox visually unchecked until confirmed.
        e.preventDefault();
        show_remote_first_confirm = true;
    } else {
        // User is disabling — browser already toggled the DOM to unchecked; just sync the store.
        badges_loc.current.qry__remote_first = false;
        show_remote_first_confirm = false;
        handle_search_trigger();
    }
}

function confirm_remote_first() {
    badges_loc.current.qry__remote_first = true;
    show_remote_first_confirm = false;
    handle_search_trigger();
}

function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}

function handle_qr_scan_result(event: {
    detail: { result: string; entry_method: string };
}) {
    let qr_scan_result = event.detail.result;
    let obj = ae_util.process_data_string(qr_scan_result);

    if (obj && obj.type && obj.id && obj.type === 'event_badge') {
        badges_loc.current.fulltext_search_qry_str = obj.id;
        handle_search_trigger();

        $events_sess.badges.show_form__search = true;
        $events_sess.badges.show_form__scan = false;
        $events_sess.badges.qr_scan_start = false;
    }
}
</script>

<div
    class="ae_group filters_and_search flex w-full flex-col items-center justify-center gap-2">
    {#if $events_sess.badges.show_form__search}
        <form
            transition:fade={{ duration: 200 }}
            onsubmit={prevent_default(() => {
                handle_search_trigger();
            })}
            autocomplete="off"
            class="search_form bg-primary-50-950 border-primary-100-900 flex w-full max-w-4xl flex-col sm:flex-row flex-wrap items-center justify-center gap-2 rounded-lg px-2 py-2 shadow-lg md:px-12">
            <div
                class="flex grow flex-col xl:flex-row flex-wrap items-center justify-center gap-2">
                {#if ($ae_loc.trusted_access && $ae_loc.edit_mode) || $ae_loc.manager_access}
                    <div transition:slide={{ duration: 200 }} class="flex flex-row flex-wrap items-center justify-center gap-1">
                        <span class="flex flex-row flex-wrap items-center justify-center gap-1">
                        <select
                            bind:value={badges_loc.current.visibility_filter}
                            onchange={handle_search_trigger}
                            class="select select-sm max-w-fit px-1 text-xs">
                            <option value="default">-- Default --</option>
                            <option value="show_hidden">Show Hidden</option>
                            {#if $ae_loc.manager_access}
                                <option value="show_all">Show Disabled + Hidden</option>
                            {/if}
                        </select>

                        <select
                            bind:value={badges_loc.current.search_badge_type_code}
                            onchange={handle_search_trigger}
                            class="select select-sm max-w-fit px-1 text-xs">
                            <option value="">-- All Badge Types --</option>
                            {#each badge_type_code_li as badge_type_code (badge_type_code.code)}
                                <option value={badge_type_code.code}
                                    >{badge_type_code.name}</option>
                            {/each}
                        </select>

                        <select
                            bind:value={badges_loc.current.qry_printed_status}
                            onchange={handle_search_trigger}
                            class="select select-sm max-w-fit px-1 text-xs">
                            <option value="all">-- All Print Status --</option>
                            <option value="printed">Printed</option>
                            <option value="not_printed">Not Printed</option>
                        </select>

                        <select
                            bind:value={badges_loc.current.qry_sort_order}
                            onchange={handle_search_trigger}
                            class="select select-sm max-w-fit px-1 text-xs">
                            <option value="">-- Default Sort --</option>
                            <option value="name_asc">Name ASC</option>
                            <option value="name_desc">Name DESC</option>
                            <option value="updated_desc">Updated DESC</option>
                            <option value="updated_asc">Updated ASC</option>
                            <option value="print_count_desc"
                                >Print Count DESC</option>
                            <option value="print_first_desc"
                                >First Printed DESC</option>
                            <option value="print_last_desc"
                                >Last Printed DESC</option>
                            <option value="badge_type_asc">Badge Type ASC</option>
                            <option value="affiliations_asc"
                                >Affiliations ASC</option>
                        </select>
                        </span>

                        <input
                            type="search"
                            placeholder="Affiliations/Company"
                            bind:value={badges_loc.current.qry_affiliations}
                            onkeyup={(e) => {
                                if (
                                    e.key === 'Enter' ||
                                    (badges_loc.current.qry_affiliations?.length ??
                                        0) >= 3
                                ) {
                                    handle_search_trigger();
                                }
                            }}
                            class="input input-sm max-w-fit px-1 text-xs" />
                    </div>
                {/if}

                <div class="flex grow flex-row flex-wrap items-center justify-center gap-2">

                    {#if (badges_loc.current.enable_search_qr && $ae_loc.edit_mode)}
                        <button
                            transition:fade={{ duration: 150 }}
                            type="button"
                            onclick={() => {
                                $events_sess.badges.show_form__search = false;
                                $events_sess.badges.show_form__scan = true;
                                $events_sess.badges.qr_scan_start = true;
                            }}
                            class="btn btn-sm preset-tonal-warning border-warning-500 border">
                            <QrCode size="1em" class="mr-1" />
                            QR Scan
                        </button>
                    {/if}

                    <!-- An extra "start" button that will just set the focus to the input form field -->
                    <button
                        type="button"
                        onclick={() => document.getElementById('badge_fulltext_search_qry_str')?.focus()}
                        aria-label="Start here — focus search field"
                        data-testid="badge-start-btn"
                        class="btn btn-sm preset-filled-secondary-200-800 font-semibold transition-opacity duration-300"
                        class:opacity-30={!!badges_loc.current.fulltext_search_qry_str}
                        class:hidden={$ae_loc.trusted_access}
                        >
                        <StepForward size="1em" class="mx-1" />
                        Start Here:
                    </button>

                    <!-- svelte-ignore a11y_autofocus -->
                    <input
                        type="search"
                        autofocus
                        placeholder="name, email, company, organization, etc."
                        id="badge_fulltext_search_qry_str"
                        bind:value={badges_loc.current.fulltext_search_qry_str}
                        autocomplete="off"
                        data-lpignore="true"
                        class="
                            input grow
                            min-w-32
                            sm:min-w-96 md:max-w-1/2
                            transition-all
                            font-mono text-lg
                            bg-red-50-900 dark:bg-red-50-950
                            focus:bg-white
                            focus:text-black
                            border border-l-2 border-r-2 border-b-3
                            border-l-success-300 border-b-success-500
                            border-r-success-300 border-t-success-300
                            dark:border-l-success-800 dark:border-b-success-800
                            preset-tonal-success
                            "
                        onkeyup={(e) => {
                            if (e.key === 'Enter') {
                                handle_search_trigger();
                            }
                        }}
                        title="Search by name, email, etc. Press Enter." />

                </div>
            </div>

            <p class="w-full text-center text-xs transition-opacity duration-200"
               class:opacity-0={(badges_loc.current.fulltext_search_qry_str ?? '').trim().length >= effective_min_chars}
               class:opacity-50={(badges_loc.current.fulltext_search_qry_str ?? '').trim().length < effective_min_chars}>
                Enter at least {effective_min_chars} character{effective_min_chars === 1 ? '' : 's'} to search
            </p>

            <div class="flex flex-row items-center justify-center gap-1">
                <button
                    type="submit"
                    disabled={($events_sess.badges.search_status === 'loading') || (badges_loc.current.fulltext_search_qry_str ?? '').trim().length < effective_min_chars}
                    class="
                    hover:text-primary-800-200 hover:bg-primary-200-800 active:bg-surface-200-700 flex items-center justify-center gap-1 px-3 py-2 text-2xl font-bold transition-all duration-1000 hover:duration-50 min-w-0 preset-tonal-success rounded-lg border border-success-200-800
                    w-48
                    disabled:opacity-50 disabled:cursor-not-allowed
                    ">
                    {#if $events_sess.badges.search_status === 'loading'}
                        <LoaderCircle class="mx-1 animate-spin" />
                    {:else}
                        <Search class="mx-1" />
                    {/if}
                    Search
                </button>

                <button
                    type="button"
                    class:opacity-0={!badges_loc.current.fulltext_search_qry_str &&
                        !badges_loc.current.search_badge_type_code &&
                        badges_loc.current.qry_printed_status === 'all' &&
                        badges_loc.current.visibility_filter === 'default'}
                    class:pointer-events-none={!badges_loc.current.fulltext_search_qry_str &&
                        !badges_loc.current.search_badge_type_code &&
                        badges_loc.current.qry_printed_status === 'all' &&
                        badges_loc.current.visibility_filter === 'default'}
                    onclick={() => {
                        badges_loc.current.fulltext_search_qry_str = '';
                        badges_loc.current.search_badge_type_code = '';
                        badges_loc.current.qry_printed_status = 'all';
                        badges_loc.current.qry_affiliations = '';
                        badges_loc.current.visibility_filter = 'default';
                        handle_search_trigger();

                        document.getElementById('badge_fulltext_search_qry_str')?.focus();
                    }}
                    class="
                    hover:text-tertiary-800-200 hover:bg-tertiary-200-800 active:bg-surface-200-700 flex items-center justify-center gap-1 px-3 py-2 text-sm font-bold transition-all duration-200 hover:duration-100 min-w-0 preset-outlined-tertiary rounded-lg border border-tertiary-200-800

                    "
                    title="Clear search query">
                    <RemoveFormatting size="1.25em" />
                    <span class="hidden md:inline"> Clear </span>
                </button>

                {#if $ae_loc.edit_mode}
                    {#if limit_steps.length > 1}
                        <div
                            transition:fade={{ duration: 150 }}
                            class="flex flex-row items-center gap-1"
                            title="Max results (edit mode override)">
                            <button
                                type="button"
                                onclick={() => {
                                    if (limit_idx > 0)
                                        badges_loc.current.qry_result_limit = limit_steps[limit_idx - 1];
                                }}
                                disabled={limit_idx <= 0}
                                class="btn btn-sm preset-outlined-surface-300-700 transition-all px-1
                                    {limit_idx <= 0 ? 'opacity-30 cursor-not-allowed' : 'opacity-60 hover:opacity-100'}">
                                <Minus size="0.85em" />
                            </button>
                            <span class="min-w-8 text-center text-xs font-semibold tabular-nums opacity-80">
                                {badges_loc.current.qry_result_limit}
                            </span>
                            <button
                                type="button"
                                onclick={() => {
                                    if (limit_idx < limit_steps.length - 1)
                                        badges_loc.current.qry_result_limit = limit_steps[limit_idx + 1];
                                }}
                                disabled={limit_idx >= limit_steps.length - 1}
                                class="btn btn-sm preset-outlined-surface-300-700 transition-all px-1
                                    {limit_idx >= limit_steps.length - 1 ? 'opacity-30 cursor-not-allowed' : 'opacity-60 hover:opacity-100'}">
                                <Plus size="0.85em" />
                            </button>
                        </div>
                    {:else}
                        <span
                            transition:fade={{ duration: 150 }}
                            class="text-xs opacity-50"
                            title="Max results for your access level">
                            Max: 25
                        </span>
                    {/if}

                    {#if $ae_loc.trusted_access}
                    <label
                        transition:fade={{ duration: 150 }}
                        title="Remote First: skip the local cache and query the server directly on every search"
                        class="bg-surface-200-800 rounded-token flex cursor-pointer items-center gap-1 px-2 py-1 text-xs font-semibold"
                        class:preset-tonal-warning={badges_loc.current.qry__remote_first}>
                        <span>Remote First</span>
                        <input
                            type="checkbox"
                            checked={badges_loc.current.qry__remote_first}
                            onclick={handle_remote_first_click}
                            title="When enabled, every search queries the server directly instead of using the local cache"
                            class="checkbox checkbox-sm" />
                    </label>
                    {/if}
                {/if}
            </div>

            {#if show_remote_first_confirm}
                <div
                    transition:slide={{ duration: 150 }}
                    class="flex w-full flex-col gap-2 rounded-md border border-warning-400 dark:border-warning-600 bg-warning-50 dark:bg-warning-900/20 px-3 py-2 text-sm">
                    <div class="flex items-start gap-2">
                        <TriangleAlert size="1em" class="mt-0.5 shrink-0 text-warning-600 dark:text-warning-400" />
                        <p class="text-warning-900 dark:text-warning-100">
                            <strong>Remote First</strong> skips the local cache and queries the server on every keystroke.
                            Results will always reflect the latest data but searches may be slower.
                            Use this only if recent changes aren't showing up in search results.
                        </p>
                    </div>
                    <div class="flex justify-end gap-2">
                        <button
                            type="button"
                            onclick={() => (show_remote_first_confirm = false)}
                            class="btn btn-sm preset-tonal-surface border border-surface-300-700">
                            Cancel
                        </button>
                        <button
                            type="button"
                            onclick={confirm_remote_first}
                            class="btn btn-sm preset-filled-warning border border-warning-600">
                            Enable Remote First
                        </button>
                    </div>
                </div>
            {/if}
        </form>
    {:else if $events_sess.badges.show_form__scan}
        <div
            transition:fade={{ duration: 200 }}
            class="bg-surface-100-900 mx-auto w-full max-w-2xl rounded-lg p-4 shadow-lg">
            <Element_qr_scanner
                bind:start_qr_scanner={$events_sess.badges.qr_scan_start}
                on_qr_scan_result={handle_qr_scan_result} />
        </div>

        {#if ($ae_loc.edit_mode)}
        <button
            type="button"
            onclick={() => {
                $events_sess.badges.show_form__search = true;
                $events_sess.badges.show_form__scan = false;
                $events_sess.badges.qr_scan_start = false;
            }}
            class="btn btn-sm preset-tonal-primary border-primary-500 border">
            <Search size="1em" class="mr-1" />
            Search
        </button>
        {/if}
    {/if}

</div>
