<script lang="ts">
	// export let data: any;
	// 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/ae_utils';
	import { api } from '$lib/api/api';
	import { liveQuery } from 'dexie';
	import { db_events } from '$lib/ae_events/db_events';
	import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/stores/ae_stores';
	import {
		events_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';

	import Element_data_store from '$lib/elements/element_data_store_v2.svelte';

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

	$events_slct.exhibit_id = null;
	$events_slct.exhibit_obj = null;

	// 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_slct.exhibit_obj &&
		$events_slct.exhibit_obj.event_exhibit_id_random &&
		($ae_loc.administrator_access ||
			($events_loc.leads.auth_exhibit_kv &&
				$events_slct.exhibit_obj &&
				$events_loc.leads.auth_exhibit_kv[$events_slct.exhibit_obj.event_exhibit_id_random]))
	) {
		disable_open_lead_retrieval_btn = false;
		disable_reset_passcode_btn = false;

		$events_sess.leads.open_href = `/events_leads/exhibit/${$events_slct.exhibit_obj.id_random}`;

		if ($events_loc.leads.auto_view) {
			goto($events_sess.leads.open_href, { invalidateAll: true });
		}
	} else {
		disable_open_lead_retrieval_btn = true;
		disable_reset_passcode_btn = true;
	}

	$: if ($events_sess.leads.entered_passcode && $events_sess.leads.entered_passcode >= 5) {
		// disable_open_lead_retrieval_btn = false;
		// Convert the passcode to a string before checking it.
		handle_check_event_exhibit_staff_passcode(String($events_sess.leads.entered_passcode));
	} else {
		disable_open_lead_retrieval_btn = true;
		// handle_check_event_exhibit_staff_passcode();
	}

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

		$events_sess.leads.open_href = '';

		if ($events_slct.exhibit_obj && entered_passcode && entered_passcode.length >= 4) {
			if ($events_slct.exhibit_obj.staff_passcode == 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 handle_update_event_exhibit_staff_passcode(exhibit_id, reset_passcode) {
		console.log(
			`*** handle_update_event_exhibit_staff_passcode() *** $events_slct.exhibit_id= ${exhibit_id} new passcode: ${reset_passcode}`
		);

		// if ($events_slct.exhibit_obj && reset_passcode && reset_passcode.length >= 4) {
		//     $events_slct.exhibit_obj.staff_passcode = reset_passcode;
		//     $events_sess.leads.entered_passcode = reset_passcode;

		//     db_events.exhibit.update($events_slct.exhibit_obj.id_random, { staff_passcode: reset_passcode })
		//     .then(function (updated) {
		//         console.log(`Updated passcode for exhibit ${$events_slct.exhibit_obj.id_random} or ${$events_slct.exhibit_id}`);
		//         disable_open_lead_retrieval_btn = false;
		//         disable_reset_passcode_btn = false;
		//     })
		//     .catch(function (error: any) {
		//         console.log('Failed to update passcode.', error);
		//         disable_open_lead_retrieval_btn = true;
		//         disable_reset_passcode_btn = true;
		//     });
		// } else {
		//     console.log('Missing selected event exhibit and or staff passcode.');
		//     disable_open_lead_retrieval_btn = true;
		//     disable_reset_passcode_btn = true;
		// }
	}
</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="preset-tonal-secondary border border-secondary-500 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 border-slate-500/10 p-2"
			>
				<!-- <h2>Exhibitor Lead Retrieval</h2> -->
				<!-- <div class="">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">
					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
							id="exhibit_list"
							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="number"
						bind:value={$events_sess.leads.entered_passcode}
						class="input w-44 m-1"
						placeholder="Exhibit passcode"
					/>

					<button
						type="submit"
						disabled={disable_open_lead_retrieval_btn}
						class="btn preset-tonal-primary border border-primary-500 m-1 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(
									$events_slct.exhibit_obj.event_exhibit_id_random,
									reset_passcode
								);
							}}
							class="btn preset-tonal-warning border border-warning-500 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>
