<script lang="ts">
export let data;
console.log(`ae_events_leads +page data:`, data);
// console.log(`ae_events_leads Data Params:`, data.url.searchParams.get('event_id'));

import { onMount } from 'svelte';
import { goto, invalidate, pushState, replaceState } from '$app/navigation';

import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import { liveQuery } from "dexie";
import { db_events } from "$lib/db_events";
import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/ae_stores';
import { events_loc, events_sess, events_slct, events_trigger } from '$lib/ae_events_stores';

import Element_data_store from '$lib/element_data_store.svelte';


let event_exhibit_obj_li = liveQuery(
    // () => db_events.exhibits.toArray()
    () => db_events.exhibits
        .where('license_max')
        // .aboveOrEqual(0)
        // .equals('99999')
        .above(0)
        .sortBy('name') // Use sortBy() instead of orderBy(). toArray() is also not needed???
        // .orderBy('name')
        // .offset(10).limit(5)
        // .toArray()
);

// This should probably be moved
if (data.url.searchParams.get('event_id')) {
    $events_slct.event_id = data.url.searchParams.get('event_id');
} else if (data.ae_loc.site_cfg_json.slct__event_id) {
    $events_slct.event_id = data.ae_loc.site_cfg_json.slct__event_id;
} else if ($events_loc.default__event_id) {
    $events_slct.event_id = $events_loc.default__event_id;
} else if ($events_slct.event_id) {
    console.log(`Event ID already set:`, $events_slct.event_id);
} else {
    console.log(`No Event ID set.`);
}

// export let event_exhibit_staff_passcode: string = '';
let disable_open_lead_retrieval_btn: boolean = true;
let disable_reset_passcode_btn: boolean = true;
let reset_passcode: string = '';

onMount(() => {
    console.log('Events Leads: +page.svelte');

    // console.log('ae_ slct:', $slct);

    let href_url = window.location.href;
    $ae_loc.href_url = href_url;
    // console.log(`$ae_loc.href_url = `, $ae_loc.href_url);

    // $slct_trigger = 'msg_parent';
    // ae_util.handle_url_and_message('event_id', $events_slct.event_id);
    // ae_util.handle_url_and_message('exhibit_id', $events_slct.exhibit_id);
    // if ($events_slct.exhibit_id) {
    //     console.log(`Got an ID. Let's do something!?`);
    //     modalStore.trigger(modal_view__exhibit_obj);
    // }
});


$: if ($events_sess.leads.entered_passcode && $events_sess.leads.entered_passcode >= 5) {
    // disable_open_lead_retrieval_btn = false;
    handle_check_event_exhibit_staff_passcode();
} else {
    disable_open_lead_retrieval_btn = true;
    // handle_check_event_exhibit_staff_passcode();
}

function handle_check_event_exhibit_staff_passcode() {
    console.log(`*** handle_check_event_exhibit_staff_passcode() *** $events_slct.exhibit_obj=`, $events_slct.exhibit_obj);

    $events_sess.leads.open_href = '';

    if ($events_slct.exhibit_obj && $events_sess.leads.entered_passcode && $events_sess.leads.entered_passcode.length >= 4) {
        if ($events_slct.exhibit_obj.staff_passcode == $events_sess.leads.entered_passcode) {
            console.log(`Passcode matched for exhibit ${$events_slct.exhibit_obj.id_random} or ${$events_slct.exhibit_id}`);
            disable_open_lead_retrieval_btn = false;

            // We should not need to be doing this here! Why???
            if (!$events_slct.exhibit_id) {
                $events_slct.exhibit_id = $events_slct.exhibit_obj.id_random;
            }

            $events_sess.leads.entered_passcode = null;
            $events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_id] = {
                key: null,
                updated_on: new Date().toISOString()
                };

            // console.log($events_slct);
            $events_sess.leads.open_href = `/events_leads/exhibit/${$events_slct.exhibit_obj.id_random}?event_id=${$events_slct.event_id}`;

            if ($events_loc.leads.auto_view) {
                goto($events_sess.leads.open_href, {invalidateAll: true});
            }
        } else {
            // console.log('Passcode does not match');
            disable_open_lead_retrieval_btn = true;
            return false;
        }
    } else {
        console.log('Missing selected event exhibit and or staff passcode.');
        disable_open_lead_retrieval_btn = true;
        return null;
    }

    if ($events_loc.leads.auto_view) {
        // open_exhibit_tracking($events_slct.exhibit_obj.id_random)
    } else {
        // console.log(document.getElementById('open_lead_retrieval_btn'));
        // document.getElementById('open_lead_retrieval_btn').focus();
    }
}


// function open_exhibit_tracking(event_exhibit_id_random) {
//     console.log(`open_exhibit_tracking() event_exhibit_id_random=${event_exhibit_id_random}`);

//     if (!event_exhibit_id_random) {
//         console.log('No event exhibit ID provided.');
//         return null;
//     }

//     if ($events_loc.leads.auto_view) {
//         goto($events_sess.leads.open_href, {invalidateAll: true});
//     } else {
//     }
// }
</script>


<section class="ae_events_leads h-full w-full flex flex-col wrap align-begin justify-start items-center space-y-4">

<h1 class="h2">Events - Leads for exhibitors</h1>

<Element_data_store
    ds_code="events__leads__overview"
    ds_type="html"
    for_type="event"
    for_id={$events_slct.event_id}
    display="block"
    class_li="variant-ghost-secondary p-2"
    />

<!-- <a href="/{$events_slct.event_id}">Event ID {$events_slct.event_id}</a> -->


{#if $event_exhibit_obj_li}
<h2 class="h3">Select your exhibit from the list</h2>
<!-- <ul>
    {#each $event_exhibit_obj_li as exhibit_obj}
        <li>
            <a href="/events_leads/exhibit/{exhibit_obj.id_random}">{exhibit_obj.name} ID {exhibit_obj.id_random}</a>
        </li>
    {/each}
</ul> -->


<div class="event_exhibit_tracking_select_exhibit space-y-6">
    <form
        on:submit|preventDefault={() => {
            $events_sess.leads.open_href = `/events_leads/exhibit/${$events_slct.exhibit_obj.id_random}?event_id=${$events_slct.event_id}`;
            goto($events_sess.leads.open_href, {invalidateAll: true});
        }}

        class="flex flex-col items-center border-2 border-primary p-2">
    <!-- <h2>Exhibitor Lead Retrieval</h2> -->
    <div>Select your exhibit booth from the list and enter passcode you were given. If it is correct you will be taken to the page for your exhibit.</div>

    <div class="m-2">
        <label for="exhibit_list" class="label">
            <!-- <span class="label">Exhibit List:</span> -->
        <select
            bind:value={$events_slct.exhibit_obj}
            class="select w-96"
            placeholder="Select your exhibit booth"
            >
            <option value="" selected>-- Nothing Selected --</option>
            {#each $event_exhibit_obj_li as event_exhibit_obj, index}
                <option value={event_exhibit_obj}>{event_exhibit_obj.name} (Booth #{event_exhibit_obj.code})</option>
            {/each}
        </select>


        </label>
    </div>

    <div class="container_group m-2">

        <input
            type="text"
            bind:value={$events_sess.leads.entered_passcode}
            class="input w-40"
            placeholder="Exhibit passcode"
            />

        <button
            type="submit"
            disabled={disable_open_lead_retrieval_btn}
            class="btn variant-ghost-primary open_lead_retrieval_btn"
            >
            <span class="fas fa-arrow-right mx-1"></span> Open Exhibitor Lead Retrieval
        </button>

        <!-- <a
            on:click|preventDefault={() => goto($events_sess.leads.open_href, {invalidateAll: true})}
            href={$events_sess.leads.open_href}
            >
            Open Exhibitor Lead Retrieval
        </a> -->
    </div>
    </form>

    {#if ($ae_loc.administrator_access && !$events_loc.show_details)}
    <div class="flex flex-col items-center">

        <span>
        <input bind:value={reset_passcode} placeholder="Reset passcode" title="Reset exhibit passcode" class="input max-w-40" />

        <button
            type="button"
            disabled={disable_reset_passcode_btn}
            on:click={() => {
                handle_update_event_exhibit_staff_passcode(exhibit_obj.event_exhibit_id_random, reset_passcode);
            }}
            class="btn variant-ghost-warning reset_passcode_btn"
            >
            <span class="fas fa-undo mx-1"></span> Reset Passcode
        </button>
        </span>
    </div>
    {/if}


</div>


<!-- <button
type="button"
on:click={() => {
    console.log(`Goto Button Clicked`);
    // goto($events_sess.leads.open_href, {invalidateAll: true});
    goto('?key=value');
}}
class="btn variant-filled-secondary"
>
Test Goto Button
</button> -->


{/if}

<!-- <Element_data_store
    ds_code="events__leads__example"
    ds_type="html"
    for_type="event"
    for_id={$events_slct.event_id}
    ds_name="Default: Events Leads Example"
    store="local"
    display="block"
    class_li="variant-ghost-surface p-2"
    try_cache={true}
    show_edit={false}
    /> -->

</section>


<style lang="postcss">
</style>
