<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,
        RemoveFormatting,
        QrCode,
        Search,
        LoaderCircle
    } from 'lucide-svelte';

    import { ae_loc, ae_api } from '$lib/stores/ae_stores';
    import { events_loc, events_sess } from '$lib/stores/ae_events_stores';
    import Element_qr_scanner_v3 from '$lib/element_qr_scanner_v3.svelte';
    import { ae_util } from '$lib/ae_utils/ae_utils';

    // ISHLT 2024 badge type codes
    let badge_type_code_li = [
        { code: 'current_member', name: 'Member' },
        { code: 'inactive_member', name: 'Non-Member' },
        { code: 'current_member_trainee', name: 'Trainee Member' },
        { code: 'inactive_member_trainee', name: 'Trainee Non-Member' },
        { code: 'ex_all', name: 'Exhibitor All Access' },
        { code: 'ex_booth', name: 'Exhibitor Booth Staff' },
        { code: 'hftx', name: 'HFTX Master Academy' },
        { code: 'mcs', name: 'MCS Master Academy' },
        { code: 'pediatric', name: 'Pediatric' },
        { code: 'guest', name: 'Guest' },
        { code: 'staff', name: 'Staff' },
        { code: 'volunteer', name: 'Volunteer' },
        { code: 'test', name: 'Test' }
    ];

    function handle_search_trigger() {
        if ($events_loc.badges.search_version === undefined) {
            $events_loc.badges.search_version = 0;
        }
        $events_loc.badges.search_version++;
    }

    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') {
            $events_loc.badges.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 flex-col items-center justify-center gap-2 w-full"
>
    {#if $events_sess.badges.show_form__search}
        <form
            onsubmit={prevent_default(() => {
                handle_search_trigger();
            })}
            autocomplete="off"
            class="search_form flex flex-row flex-wrap gap-1 items-center justify-center w-full max-w-7xl px-2 md:px-12 py-2 preset-tonal-success rounded-lg shadow-sm"
        >
            <div
                class="flex flex-col md:flex-row items-center justify-center gap-1 grow"
            >
                {#if $ae_loc.trusted_access}
                    <select
                        bind:value={$events_loc.badges.search_badge_type_code}
                        onchange={handle_search_trigger}
                        class="select select-sm text-xs px-1 max-w-fit"
                    >
                        <option value="">-- All Badge Types --</option>
                        {#each badge_type_code_li as badge_type_code}
                            <option value={badge_type_code.code}
                                >{badge_type_code.name}</option
                            >
                        {/each}
                    </select>

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

                    <select
                        bind:value={$events_loc.badges.qry_sort_order}
                        onchange={handle_search_trigger}
                        class="select select-sm text-xs px-1 max-w-fit"
                    >
                        <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>

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

                <input
                    type="search"
                    placeholder="name, email"
                    id="badge_fulltext_search_qry_str"
                    bind:value={$events_loc.badges.fulltext_search_qry_str}
                    autocomplete="off"
                    data-lpignore="true"
                    class="input text-lg font-mono grow transition-all"
                    onkeyup={(e) => {
                        if (e.key === 'Enter') {
                            handle_search_trigger();
                        }
                    }}
                    title="Search by name, email, etc. Press Enter."
                />
            </div>

            <div class="flex flex-row items-center justify-center gap-1">
                <button
                    type="submit"
                    class="btn btn-lg preset-tonal-success border border-success-500 hover:preset-tonal-success text-2xl font-bold w-48 transition-all"
                >
                    {#if $events_sess.badges.search_status === 'loading'}
                        <LoaderCircle class="animate-spin mx-1" />
                    {:else}
                        <Search class="mx-1" />
                    {/if}
                    Search
                </button>

                <button
                    type="button"
                    class:hidden={!$events_loc.badges.fulltext_search_qry_str &&
                        !$events_loc.badges.search_badge_type_code &&
                        $events_loc.badges.qry_printed_status === 'all'}
                    onclick={() => {
                        $events_loc.badges.fulltext_search_qry_str = '';
                        $events_loc.badges.search_badge_type_code = '';
                        $events_loc.badges.qry_printed_status = 'all';
                        $events_loc.badges.qry_affiliations = '';
                        handle_search_trigger();
                    }}
                    class="btn btn-sm text-xs preset-outlined-tertiary-100-900 hover:preset-filled-tertiary-100-900 transition-all"
                    title="Clear search query"
                >
                    <RemoveFormatting size="1.25em" />
                    <span class="hidden md:inline"> Clear </span>
                </button>
            </div>
        </form>
    {:else if $events_sess.badges.show_form__scan}
        <div
            class="w-full max-w-2xl mx-auto p-4 bg-surface-100-900 rounded-lg shadow-lg"
        >
            <Element_qr_scanner_v3
                bind:start_qr_scanner={$events_sess.badges.qr_scan_start}
                on_qr_scan_result={handle_qr_scan_result}
            />
        </div>
    {/if}

    <div
        class="flex flex-row flex-wrap items-center justify-center gap-2 opacity-70 hover:opacity-100 transition-all"
    >
        {#if $events_sess.badges.show_form__search}
            <button
                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-primary border border-primary-500"
            >
                <QrCode size="1em" class="mr-1" />
                QR Scan
            </button>
        {:else}
            <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 border-primary-500"
            >
                <Search size="1em" class="mr-1" />
                Search
            </button>
        {/if}

{#if $ae_loc.edit_mode}
            <label
                class="flex items-center gap-1 cursor-pointer bg-surface-200-800 px-2 py-1 rounded-token text-xs font-semibold"
            >
                <span> Remote First </span>
                <input
                    type="checkbox"
                    bind:checked={$events_loc.badges.qry__remote_first}
                    onchange={handle_search_trigger}
                    class="checkbox checkbox-sm"
                />
            </label>
        {/if}
    </div>
</div>
