<script lang="ts">
	interface Props {
		event_id: string;
		use_id_li?: boolean;
		event_badge_id_li?: Array<string>;
		// event_badge_obj_li?: Array<any>;
		search_status?: string;
		search_complete?: boolean;
		qry_str?: string;
		qry_type_code?: string;
		log_lvl?: number;
	}

	let {
		event_id,
		use_id_li = $bindable(true),
		event_badge_id_li = $bindable([]),
		// event_badge_obj_li = $bindable(),
		search_status = $bindable('idle'),
		search_complete = $bindable(true),
		qry_str = $bindable(''),
		qry_type_code = $bindable(''),
		log_lvl = 0
	}: Props = $props();

	// *** Import Svelte specific

	// *** Import other supporting libraries
	import {
		ArrowDown01,
		ArrowDown10,
		ArrowDownUp,
		BetweenVerticalEnd,
		BetweenVerticalStart,
		BookHeart,
		BookImage,
		Bookmark,
		BookOpenText,
		BriefcaseBusiness,
		Check,
		Copy,
		Expand,
		Eye,
		EyeOff,
		Flag,
		FlagOff,
		FilePlus,
		Fingerprint,
		Globe,
		Library,
		MessageSquareWarning,
		Minus,
		Notebook,
		Pencil,
		Plus,
		RemoveFormatting,
		SquareLibrary,
		Shapes,
		Share2,
		ShieldCheck,
		ShieldMinus,
		Siren,
		Skull,
		Tags,
		Target,
		ToggleLeft,
		ToggleRight,
		Trash2,
		TypeOutline,
		X
	} from '@lucide/svelte';

	import type { key_val } from '$lib/stores/ae_stores';
	// import { ae_util } from '$lib/ae_utils/ae_utils';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import {
		events_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';
	import { events_func } from '$lib/ae_events_functions';

	// *** Variables
	let ae_promises: key_val = $state({});
	let ae_tmp: key_val = $state({});
	let ae_triggers: key_val = $state({});

	// 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' }
	];

	// *** Functions and Logic
	function preventDefault<T extends Event>(fn: (event: T) => void) {
		return function (event: T) {
			event.preventDefault();
			fn(event);
		};
	}

	// Trigger doing a search query for event badges
	$effect(() => {
		if (ae_triggers.event_badge_qry) {
			ae_triggers.event_badge_qry = false;
			search_status = 'loading';
			search_complete = false;
			event_badge_id_li = [];

			// qry_str = $events_loc.badges.fulltext_search_qry_str ?? '';
			// qry_type_code = $events_sess.badges.search_badge_type_code ?? '';

			if (log_lvl) {
				console.log(
					`Triggered: event_badge_qry: ft search qry str:=${$events_loc.badges.fulltext_search_qry_str}`
				);
			}

			// ae_promises.load__event_badge_obj_li = events_func.qry__event_badge({
			ae_promises.load__event_badge_obj_li = events_func
				.search__event_badge({
					api_cfg: $ae_api,
					event_id: event_id,
					// qry_str: $events_loc.badges.fulltext_search_qry_str,
					type_code: $events_sess.badges.search_badge_type_code,
					fulltext_search_qry_str: $events_loc.badges.fulltext_search_qry_str,

					// qry_created_on: null,
					// qry_alert: null,
					// qry_priority: null,
					// qry_type: and_type,

					// enabled: $events_loc.recovery_meetings.qry__enabled,
					// hidden: $events_loc.recovery_meetings.qry__hidden,
					// order_by_li: $events_loc.recovery_meetings.qry__order_by_li,
					// limit: $events_loc.recovery_meetings.qry__limit,
					// try_cache: try_cache,
					log_lvl: log_lvl
				})
				.then(function (search_results) {
					search_status = 'processing';
					let tmp_event_badge_id_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

					for (let i = 0; i < search_results.length; i++) {
						let event_badge_obj = search_results[i];
						let event_badge_id_random = event_badge_obj.event_badge_id_random;
						tmp_event_badge_id_li.push(event_badge_id_random);
					}
					event_badge_id_li = tmp_event_badge_id_li;
					console.log('event_badge_id_li', event_badge_id_li);

					$events_sess.badge_li = search_results;

					return search_results;
				})
				.finally(() => {
					search_status = 'done';
					search_complete = true;
				});
		}
	});

	// Updated 2024-06-12 late
	$effect(() => {
		if (ae_triggers.event_badge_qry == 'load__event_badge_obj_li' && $events_slct.event_id) {
			console.log(`load__event_badge_obj_li() $events_slct.event_id=${$events_slct.event_id}`);
			log_lvl = 1;
			ae_triggers.event_badge_qry = null;

			if ($events_loc.badges.save_search_text) {
				if (log_lvl) {
					console.log(`*** Save search text *** ${$events_loc.badges.save_search_text}`);
				}
				$events_loc.badges.saved_search__badge = $events_loc.badges.fulltext_search_qry_str;
				$events_loc.badges.saved_search__badge_location_name =
					$events_sess.badges.location_name_qry_str;
			}

			if ($events_loc.badges.fulltext_search_qry_str?.length > 2) {
				console.log('*** Search string is valid ***');
				process_search_string($events_loc.badges.fulltext_search_qry_str);
			} else if ($ae_loc.authenticated_access) {
				console.log('*** Administrator Access or Trusted Access ***');
				process_search_string($events_loc.badges.fulltext_search_qry_str);
			} else {
				console.log('*** Check permissions and or search string. Not allowed or too short. ***');
				$events_slct.event_badge_obj_li = [];
				event_badge_id_li = [];
			}
		}

		// if ($events_sess.badges.status_qry__search == 'done' && $events_slct?.event_badge_obj_li) {
		log_lvl = 1;
		if (ae_triggers.event_badge_qry == 'search_done') {
			ae_triggers.event_badge_qry = null;
			$events_sess.badges.status_qry__search = null;

			if (log_lvl) {
				console.log('TEST search done: Pulling out the event_badge_id_randoms...');
			}

			// We need to loop through the array of objects and get the event_badge_id_random from each object a new list of event_badge_id_randoms. Then we can use this list to get the full objects from the database.
			let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
			if ($events_slct.event_badge_obj_li && $events_slct.event_badge_obj_li.length) {
				event_badge_id_li = [];
				// console.log(`TEST SEARCH - Get ids:`, $events_slct.event_badge_obj_li);
				for (let i = 0; i < $events_slct.event_badge_obj_li.length; i++) {
					tmp_li.push($events_slct.event_badge_obj_li[i].event_badge_id_random);
				}
			}
			event_badge_id_li = tmp_li;
			console.log(`TEST search results: event_badge_id_li`, $state.snapshot(event_badge_id_li));
		}
	});

	// function process_search_string(search_str: string) {
	//     if (log_lvl) {
	//         console.log(`process_search_string() search_str=${search_str}`);
	//     }

	//     if (search_str?.length) {
	//         // console.log(`*** Search string length: ${search_str.length} ***`);
	//     } else {
	//         // console.log(`*** Search string is empty ***`);
	//     }

	//     // let type_code = $events_sess.badges.search_badge_type_code;

	//     // let search_str = $events_loc.badges.fulltext_search_qry_str.trim();

	//     let search_method = 'lk'; // 'ft', 'lk', 'eq'
	//     let ft_search_str_new = '';
	//     let lk_search_str_new = '';

	//     if (search_method == 'ft') {
	//         // Add quotes around the search string to make it an exact match.
	//         ft_search_str_new = `${search_str}`;
	//         // ft_search_str_new = `"${search_str}"`;
	//     } else if (search_method == 'lk') {
	//         if (search_str == null) {
	//             search_str = '';
	//         }
	//         // Add a wildcard to the search string to make it a like match.
	//         lk_search_str_new = search_str.trim().replace(',', ' ').replace(';', ' ').replaceAll('  ', '%').replaceAll(' ', '%');
	//         lk_search_str_new = `%${lk_search_str_new}%`;
	//     }

	//     if (log_lvl) {
	//         // console.log(`*** Search method: ${search_method} ***`);
	//         console.log(`*** Search string: ${search_str} ***`);
	//         // console.log(`*** Fulltext search string: ${ft_search_str_new} ***`);
	//         // console.log(`*** Like search string: ${lk_search_str_new} ***`);
	//     }

	//     let type_code = '';
	//     if ($events_sess.badges.type_code_qry_str?.length) {
	//         type_code = $events_sess.badges.type_code_qry_str;
	//         console.log(`Type code: ${type_code}`);
	//     }

	//     handle_search__event_badge({
	//         ft_search_str: ft_search_str_new,
	//         lk_search_str: lk_search_str_new,
	//         and_lk_type_code: type_code,
	//         // fulltext_search_qry_str: ft_search_str_new,
	//         // ft_presenter_search_qry_str: null,
	//         // like_search_qry_str: lk_search_str_new,
	//         // like_presentation_search_qry_str: lk_search_str_new,
	//         // like_presenter_search_qry_str: lk_search_str_new,
	//         // params: params,
	//         try_cache: true,
	//         log_lvl: log_lvl,
	//     });
	// }

	async function handle_search__event_badge({
		ft_search_str = '',
		lk_search_str = '',
		and_lk_type_code = '',
		search_delay = 0,
		max_tries = 5,
		enabled = $events_loc.badges.qry_enabled ?? 'enabled',
		hidden = $events_loc.badges.qry_hidden ?? 'not_hidden',
		limit = $events_loc.badges.qry_limit__badges ?? 35,
		try_cache = true,
		log_lvl = 0
	}: {
		ft_search_str?: string;
		lk_search_str?: string;
		and_lk_type_code?: string;
		search_delay?: number; // In milliseconds
		max_tries?: number;
		enabled?: 'enabled' | 'all' | 'not_enabled' | undefined;
		hidden?: 'hidden' | 'all' | 'not_hidden' | undefined;
		limit?: number;
		try_cache?: boolean;
		log_lvl?: number;
	}) {
		if (log_lvl) {
			console.log('handle_search__event_badge()');
		}

		if (
			$events_sess.badges?.status_qry__search != null &&
			$events_sess.badges?.status_qry__search != 'done'
		) {
			// WARNING: This is a temporary fix for the search string. It needs to be fixed in the future. Using lk_search_str for now.
			$events_sess.badges.status_qry__last_request_str = lk_search_str;

			// We want to delay the initial search request to give the previous search request to finish.
			let random_delay = Math.floor(Math.random() * 50);
			search_delay += 50 + random_delay;
		}

		// log_lvl = 1;

		let count = 0;
		let request_loop = setInterval(() => {
			count++;
			if (log_lvl) {
				console.log(`*** TEST SEARCH - Search delay: ${search_delay} *** loop count=${count}`);
			}
			if (count >= max_tries) {
				console.log('*** TEST SEARCH - Max tries reached ***');
				clearInterval(request_loop);
			}

			if (
				$events_sess.badges?.status_qry__search != null &&
				$events_sess.badges?.status_qry__search != 'done'
			) {
				let random_delay = Math.floor(Math.random() * 25);
				search_delay += 25 + random_delay;
				console.log(
					`*** TEST SEARCH - $events_sess.badges.status_qry__search == loading wait *** search_delay=${search_delay}`
				);
				// $events_sess.status_qry__last_request_str = lk_search_str;
			} else {
				// console.log('*** TEST SEARCH - $events_sess.badges.status_qry__search != loading ***');

				ae_triggers.event_badge_qry = 'loading_search_results';
				$events_sess.badges.status_qry__search = 'loading';

				event_badge_id_li = []; // Resetting this seems to help trigger the new results to show correctly???

				search_submit_results = events_func
					.search__event_badge({
						api_cfg: $ae_api,
						event_id: $events_slct.event_id,
						// type_code: type_code,
						fulltext_search_qry_str: ft_search_str,
						ft_presenter_search_qry_str: null,
						like_search_qry_str: lk_search_str,
						like_presentation_search_qry_str: lk_search_str,
						like_presenter_search_qry_str: lk_search_str,
						like_poc_name_qry_str: lk_search_str,
						// external_event_id: $events_loc.badges.default__external_registration_id,
						location_name: and_lk_location_name,
						enabled: enabled,
						hidden: hidden,
						limit: limit,
						try_cache: try_cache,
						log_lvl: log_lvl
					})
					.then(function (search_results) {
						// Processing the results from the search.
						ae_triggers.event_badge_qry = 'process_search_results';
						$events_sess.badges.status_qry__search = 'processing';
						$events_slct.event_badge_obj_li = search_results;
					})
					.finally(() => {
						// Finally done with the search.
						ae_triggers.event_badge_qry = 'search_done';
						$events_sess.badges.status_qry__search = 'done';
					});
				clearInterval(request_loop);
			}
		}, search_delay);
	}
</script>

<section
	class="
    m-2 p-2 md:px-12
    flex flex-col sm:flex-row gap-1 items-center justify-center
    min-w-sm w-full max-w-7xl
    preset-tonal-success
    "
>
	<span class="text-sm text-gray-500 hidden"> Search: </span>

	{#if $events_sess.badges.show_form__search}
		<form
			onsubmit={preventDefault(() => {
				// ae_triggers.event_badge_qry = 'load__event_badge_obj_li';
				ae_triggers.event_badge_qry = true;
			})}
			autocomplete="off"
			class="
        form grow
        flex flex-row flex-wrap gap-1 items-center justify-center
        w-full
        "
		>
			<span class="flex flex-col md:flex-row items-center justify-center gap-1">
				{#if $ae_loc.trusted_access && badge_type_code_li}
					<select
						bind:value={qry_type_code}
						onchange={() => {
							// ae_triggers.event_badge_qry = 'load__event_badge_obj_li';
							ae_triggers.event_badge_qry = true;
						}}
						class="select 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>
				{/if}

				<!--
    class="input text-xl hover:text-3xl font-bold font-mono w-96"
    hover:w-2/5
    -->
				<input
					type="search"
					placeholder="name, email, affiliations"
					id="badge_fulltext_search_qry_str"
					name="fulltext_search_qry_str"
					bind:value={qry_str}
					autofocus
					suggest="off"
					data-lpignore="true"
					class="input text-1xl hover:font-bold font-mono w-fit sm:w-96 transition-all"
					onkeyup={() => {
						if ($events_loc.badges.fulltext_search_qry_str.length >= 7) {
							ae_triggers.event_badge_qry = true;
						}
					}}
					title="Enter at least 3 characters to search. Search by name, email, affiliations, etc."
				/>
			</span>

			<span class="flex flex-row flex-wrap 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"
					onclick={() => {
						ae_triggers.event_badge_qry = true;
					}}
				>
					{#if !search_complete}
						<span class="fas fa-spinner fa-spin mx-1"></span>
					{:else}
						<!-- Nothing -->
						<span class="fas fa-search mx-1"></span>
					{/if}
					Search
				</button>

				<!-- Clear search text button -->
				<button
					type="button"
					class:hidden={!$events_loc.badges.fulltext_search_qry_str}
					onclick={() => {
						console.log(
							`TESTING - 1 - Cleared search query: ${$events_loc.badges.fulltext_search_qry_str}`
						);
						$events_loc.badges.fulltext_search_qry_str = '';
						console.log(
							`TESTING - 2 - Cleared search query: ${$events_loc.badges.fulltext_search_qry_str}`
						);
						ae_triggers.event_badge_qry = true;
					}}
					class="
        btn btn-sm text-xs
        preset-outlined-tertiary-100-900
        hover:preset-filled-tertiary-100-900
        transition-all
        "
					title="Clear search query text"
				>
					<RemoveFormatting size="1.25em" class="text-neutral-800/60 dark:text-neutral-50/60" />
					<span class="hidden md:inline"> Clear </span>

					{#await ae_promises.load__event_badge_obj_li}
						<span class="text-xs text-gray-500 italic"> Loading... </span>
					{:then load_result}
						{#if load_result === null}
							<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
								No entries found - null
							</span>
						{:else if load_result?.length === 0}
							<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
								No entries found
							</span>
						{:else if event_badge_id_li?.length === 0}
							<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
								Enter to search
							</span>
						{:else}
							<span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
								{load_result?.length ?? 0} found
							</span>
						{/if}
					{:catch error}
						<span class="text-xs text-red-600/80 dark:text-red-400/80 italic">
							Error loading entries.
						</span>
					{/await}
				</button>
			</span>
		</form>

		<!-- **BEGIN** Scan Form -->
	{:else if $events_sess.badges.show_form__scan}
		Not implemented yet.
	{/if}

	<div class="opacity-50 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__search_results = 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 transition-all"
			>
				<span class="fas fa-qrcode"></span>
				QR Scan
			</button>
		{:else if $events_sess.badges.show_form__scan}
			<button
				type="button"
				onclick={() => {
					$events_sess.badges.show_form__search = true;
					$events_sess.badges.show_form__search_results = false;
					$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 transition-all"
			>
				<span class="fas fa-search"></span>
				Search
			</button>
		{/if}

		<!-- Show toggle for using the id list or not: use_id_li -->
		<button
			type="button"
			onclick={() => {
				use_id_li = !use_id_li;
				console.log(`Toggled use_id_li=${use_id_li}`);
			}}
			class="btn btn-sm preset-tonal-secondary border border-secondary-500 transition-all"
			title="Toggle using the ID list or not."
		>
			{#if use_id_li}
				<span class="fas fa-toggle-on text-green-600"></span>
			{:else}
				<span class="fas fa-toggle-off text-red-600"></span>
			{/if}
			Use ID List
		</button>
	</div>
</section>
