<script lang="ts">
	// export let data: any;
	// console.log(`ae_events_leads exhibit [slug] leads_list.svelte data:`, data);

	import type { key_val } from '$lib/stores/ae_stores';
	// import { ae_util } from '$lib/ae_utils/ae_utils';
	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 { events_func } from '$lib/ae_events_functions';

	import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';
	import Leads_view_lead from './leads_view_lead.svelte';

	let ae_promises: key_val = {};

	// These will likely be used for patch/update triggers. Maybe delete?
	let ae_triggers: key_val = {
		priority: {},
		sort: {},
		show_hidden: {}
	};

	// The lq__ prefix is used to indicate that this is a liveQuery object and it should use the $ prefix when referencing the object.
	let lq__event_exhibit_obj = liveQuery(() => db_events.exhibit.get($events_slct.exhibit_id));

	// let l_event_exhibit_tracking_obj = liveQuery(
	//     () => db_events.exhibit_tracking.get($events_slct.exhibit_tracking_id)
	// );

	// Version 1: This is the version that works
	// let event_exhibit_tracking_obj_li = liveQuery(
	//     // () => db_events.exhibit.toArray()
	//     () => db_events.exhibit_tracking
	//         // .where('enable')
	//         // .aboveOrEqual(0)
	//         // .equals(true)
	//         .where('event_exhibit_id_random')
	//         .equals($events_slct.exhibit_id)
	//         // .above(0)
	//         .sortBy('created_on')
	//         // .orderBy('name')
	//         // .offset(10).limit(5)
	//         // .toArray()
	// );

	// Testing examples:
	// Use sortBy() instead of orderBy()
	// toArray() is also not needed???

	// .where({event_exhibit_id_random: $events_slct.exhibit_id, enable: true, hide: false})
	// .where({event_exhibit_id_random: $events_slct.exhibit_id})
	// .where('event_exhibit_id_random').equals($events_slct.exhibit_id)
	// .and('enable').equals(true)
	// .reverse()
	// .sortBy('updated_on')
	// .reverse()
	// .sortBy('created_on')
	// .toArray()
	// .sortBy('created_on')
	// .reverse()
	// .sortBy('priority') // , 'sort', 'created_on', 'updated_on')

	// () => db_events.exhibit.toArray()

	// Version 2: This needs work...
	// This is using Dexie JS as a wrapper for IndexedDB
	// This should only show exhibit_tracking objects that are enabled and not hidden.
	// The final results should be sorted by: priority DESC, sort ASC, created_on DESC, updated_on DESC
	let lq__event_exhibit_tracking_obj_li = liveQuery(
		() =>
			db_events.exhibit_tracking
				.where({ event_exhibit_id_random: $events_slct.exhibit_id })
				.and((x) => x.enable == !$events_loc.leads.show_not_enabled)
				.sortBy('sort')
		// .reverse()
		// .sortBy('priority')

		// .orderBy("priority")
		// .orderBy("sort")
		// .orderBy("created_on", "desc")
		// .orderBy("updated_on", "desc")
		// .sortBy('priority') // Initial sort
		// .thenBy('created_on', 'desc')
		// .thenBy('sort')      // Secondary sort
		// .thenBy('updated_on', 'desc')
	);

	// let update_submit_results = null;

	// Once this component is mounted we need to start a loop that runs every X seconds to refresh the leads list for the exhibit.
	// console.log('Start the loop to refresh the leads list for the exhibit.');
	console.log('Refresh interval:', $events_loc.leads.refresh_interval__tracking_li ?? 'not set');
	let refresh_leads_list = setInterval(function () {
		console.log('Refresh the leads list for the exhibit.');
		events_func.handle_load_ae_obj_li__exhibit_tracking({
			api_cfg: $ae_api,
			exhibit_id: $events_slct.exhibit_id,
			params: { enabled: 'all' }
		});
	}, $events_loc.leads.refresh_interval__tracking_li ?? 35000);
</script>

<section class="tab__leads_list flex flex-col wrap justify-center items-center space-y-4">
	{#if $events_slct.exhibit_id && $events_slct.exhibit_obj}
		<h2 class="h3">
			<span class="fas fa-clipboard-list-check"></span>
			{$lq__event_exhibit_tracking_obj_li?.length}
			Leads for {$lq__event_exhibit_obj?.name}
		</h2>

		<!-- <div class="border border-slate-500/10 p-2 variant-soft-warning">This section is not fully enabled for ISHLT 2024 at this time. You can not add new leads and changes are limited.</div> -->

		<div class="flex flex-row gap-1">
			<!-- {#if $ae_loc.trusted_access} -->

			<button
				on:click={async () => {
					console.log('Show Hidden Leads');
					$events_loc.leads.show_hidden = !$events_loc.leads.show_hidden;

					console.log('$events_loc.leads.show_hidden:', $events_loc.leads.show_hidden);
				}}
				class="btn btn-sm preset-tonal"
			>
				{#if $events_loc.leads.show_hidden}
					<span class="fas fa-eye-slash m-1"></span>
					Hide Archived?
				{:else}
					<span class="fas fa-eye m-1"></span>
					Show All Leads?
				{/if}
			</button>

			<!-- {/if} -->

			{#if $ae_loc.trusted_access}
				<button
					on:click={async () => {
						console.log('Show Enabled Leads');
						$events_loc.leads.show_not_enabled = !$events_loc.leads.show_not_enabled;

						console.log('$events_loc.leads.show_not_enabled:', $events_loc.leads.show_not_enabled);
					}}
					class="btn btn-sm preset-tonal"
				>
					<span class="fas fa-eye m-1"></span>
					{$events_loc.leads.show_not_enabled ? 'Show Enabled' : 'Show Not Enabled'} Leads?
				</button>
			{/if}

			<button
				type="button"
				on:click={() => {
					if (!confirm('Download data exported to an Excel file?')) {
						return false;
					}
					ae_promises.download__exhibit_tracking_export =
						events_func.handle_download_export__event_exhibit_tracking({
							api_cfg: $ae_api,
							exhibit_id: $events_slct.exhibit_id,
							file_type: 'Excel',
							return_file: true,
							filename: `lead_retrieval_export_${$events_slct.exhibit_obj.name.replaceAll(' ', '_')}.xlsx`,
							auto_download: true,
							log_lvl: 2
						});

					// get_event_exhibit_tracking_export({ 'event_exhibit_id': $events_slct.exhibit_id, file_type: 'Excel', 'return_file': true, filename: `lead_retrieval_export_${$events_slct.exhibit_obj.name.replaceAll(' ', '_')}.xlsx`, auto_download: true, log_lvl: 2 });
					// .replace(' ', '_')
				}}
				disabled={!$events_slct.exhibit_obj.priority}
				class="btn btn-sm preset-tonal-primary border border-primary-500 w-48 mb-1 export_data_btn"
				title={`Download leads data for ${$events_slct.exhibit_obj.name}`}
			>
				{#await ae_promises.download__exhibit_tracking_export}
					<span class="fas fa-spinner fa-spin"></span>
					<!-- <span class="loading-text">
        Downloading...
    </span> -->
				{:then}
					<!-- Done? -->
				{/await}
				<span class="fas fa-download mx-1"></span> Export Data
			</button>
		</div>
		<!-- END: flex flex-row -->

		{#if $lq__event_exhibit_tracking_obj_li}
			<table class="table table-compact min-w-min">
				<thead>
					<tr>
						<th class="star text-center">Star</th>
						<th class="rank text-center">Rank</th>
						<th class="person text-center">Person</th>
					</tr>
				</thead>

				<tbody>
					{#each $lq__event_exhibit_tracking_obj_li as event_exhibit_tracking_obj, index}
						<!-- flex flex-row justify-center items-center m-auto -->
						<tr
							class:hidden={event_exhibit_tracking_obj.hide && !$events_loc.leads.show_hidden}
							class:fade_50={event_exhibit_tracking_obj.hide}
						>
							<td class="star text-center">
								<!-- <span class="star_container flex flex-col justify-center items-center m-auto"> -->

								<!-- Priority (star) means this should be sorted at the top of lists. -->
								<Element_ae_crud
									bind:trigger_patch={
										ae_triggers.priority[
											event_exhibit_tracking_obj?.event_exhibit_tracking_id_random
										]
									}
									api_cfg={$ae_api}
									object_type={'event_exhibit_tracking'}
									object_id={event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}
									field_name={'priority'}
									field_type={'button'}
									field_value={$events_slct.exhibit_tracking_obj.priority}
									allow_null={false}
									hide_edit_btn={true}
									outline_element={false}
									show_crud={false}
									display_inline={true}
									class_li={'m-1'}
									on:ae_crud_updated={(e) => {
										console.log(`ae_crud_updated event:`, e.detail);
										events_func.handle_load_ae_obj_id__exhibit_tracking({
											api_cfg: $ae_api,
											exhibit_tracking_id: $events_slct.exhibit_tracking_id
										});
									}}
								>
									<button
										type="button"
										on:click={() => {
											console.log(
												`Updating priority for event_exhibit_tracking_id: ${event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}`
											);

											$events_slct.exhibit_tracking_id =
												event_exhibit_tracking_obj.event_exhibit_tracking_id_random;
											$events_slct.exhibit_tracking_obj = event_exhibit_tracking_obj;

											$events_slct.exhibit_tracking_obj.priority =
												!$events_slct.exhibit_tracking_obj.priority;

											ae_triggers.priority[
												event_exhibit_tracking_obj?.event_exhibit_tracking_id_random
											] = true;
										}}
										class="btn btn-sm preset-tonal-tertiary"
									>
										{@html event_exhibit_tracking_obj?.priority
											? '<span class="fas fa-star m-1"></span>'
											: '<span class="far fa-star"></span>'}
									</button>
								</Element_ae_crud>
							</td>

							<!-- text-center align-middle -->
							<td class="ranking text-center">
								<!-- BEGIN: Ranking in table -->
								<div
									class="ranking_container flex flex-col lg:flex-row justify-stretch items-center"
								>
									<!-- Sort (ranking) means this should be sorted in the list based on the number. 0 is the top of the list. -->

									<Element_ae_crud
										bind:trigger_patch={
											ae_triggers.sort[event_exhibit_tracking_obj?.event_exhibit_tracking_id_random]
										}
										api_cfg={$ae_api}
										object_type={'event_exhibit_tracking'}
										object_id={event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}
										field_name={'sort'}
										field_type={'button'}
										field_value={$events_slct.exhibit_tracking_obj.sort}
										allow_null={false}
										hide_edit_btn={true}
										outline_element={false}
										show_crud={false}
										display_inline={true}
										class_li={'m-1'}
										on:ae_crud_updated={(e) => {
											console.log(`ae_crud_updated event:`, e.detail);
											events_func.handle_load_ae_obj_id__exhibit_tracking({
												api_cfg: $ae_api,
												exhibit_tracking_id: $events_slct.exhibit_tracking_id
											});
										}}
									>
										<button
											type="button"
											on:click={() => {
												console.log(
													`Updating sort for event_exhibit_tracking_id: ${event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}`
												);

												$events_slct.exhibit_tracking_id =
													event_exhibit_tracking_obj.event_exhibit_tracking_id_random;
												$events_slct.exhibit_tracking_obj = event_exhibit_tracking_obj;

												if ($events_slct.exhibit_tracking_obj.sort < 1) {
													$events_slct.exhibit_tracking_obj.sort = 0;
												} else {
													$events_slct.exhibit_tracking_obj.sort -= 1;
												}

												ae_triggers.sort[
													event_exhibit_tracking_obj?.event_exhibit_tracking_id_random
												] = true;
											}}
											disabled={event_exhibit_tracking_obj?.sort < 1}
											class="btn btn-sm preset-tonal-secondary"
										>
											<span class="fas fa-arrow-up" title="Move up"></span>
										</button>
									</Element_ae_crud>

									<span class="exhibit_tracking__sort m-0 lg:mx-1"
										>{event_exhibit_tracking_obj.sort ?? ''}</span
									>

									<Element_ae_crud
										bind:trigger_patch={
											ae_triggers.sort[event_exhibit_tracking_obj?.event_exhibit_tracking_id_random]
										}
										api_cfg={$ae_api}
										object_type={'event_exhibit_tracking'}
										object_id={event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}
										field_name={'sort'}
										field_type={'button'}
										field_value={$events_slct.exhibit_tracking_obj.sort}
										allow_null={false}
										hide_edit_btn={true}
										outline_element={false}
										show_crud={false}
										display_inline={true}
										class_li={'m-1'}
										on:ae_crud_updated={(e) => {
											console.log(`ae_crud_updated event:`, e.detail);
											events_func.handle_load_ae_obj_id__exhibit_tracking({
												api_cfg: $ae_api,
												exhibit_tracking_id: $events_slct.exhibit_tracking_id
											});
										}}
									>
										<button
											type="button"
											on:click={() => {
												console.log(
													`Updating sort for event_exhibit_tracking_id: ${event_exhibit_tracking_obj?.event_exhibit_tracking_id_random}`
												);

												$events_slct.exhibit_tracking_id =
													event_exhibit_tracking_obj.event_exhibit_tracking_id_random;
												$events_slct.exhibit_tracking_obj = event_exhibit_tracking_obj;

												if ($events_slct.exhibit_tracking_obj.sort >= 5) {
													$events_slct.exhibit_tracking_obj.sort = 5;
												} else {
													$events_slct.exhibit_tracking_obj.sort += 1;
												}

												ae_triggers.sort[
													event_exhibit_tracking_obj?.event_exhibit_tracking_id_random
												] = true;
											}}
											disabled={event_exhibit_tracking_obj.sort >= 5}
											class="btn btn-sm preset-tonal-secondary"
										>
											<span class="fas fa-arrow-down" title="Move down"></span>
										</button>
									</Element_ae_crud>

									<!-- <button
                on:click={() => {
                    $events_slct.exhibit_tracking_id = event_exhibit_tracking_obj.event_exhibit_tracking_id_random;

                    db_events.exhibit_tracking.get($events_slct.exhibit_tracking_id)
                    .then((event_exhibit_tracking_obj) => {
                        console.log('event_exhibit_tracking_obj:', event_exhibit_tracking_obj);
                        if (event_exhibit_tracking_obj.sort > 5) {
                            event_exhibit_tracking_obj.sort = 5;
                        } else {
                            event_exhibit_tracking_obj.sort += 1;
                        }
                        db_events.exhibit_tracking.put(event_exhibit_tracking_obj);
                    });
                }}
                disabled={event_exhibit_tracking_obj.sort >= 5}
                class="btn btn-sm variant-soft-secondary"
                >
                <span class="fas fa-arrow-down" title="Move down"></span>
            </button> -->
								</div>
							</td>
							<!-- END: Ranking in table -->

							<td class="person">
								<div
									class="person_container flex flex-col 2xl:flex-row gap-1 flex-wrap justify-between"
								>
									<button
										on:click={() => {
											$events_slct.exhibit_tracking_id =
												event_exhibit_tracking_obj.event_exhibit_tracking_id_random;
											$events_slct.exhibit_tracking_obj = event_exhibit_tracking_obj;
											$events_sess.leads.show_form__view_lead = $events_slct.exhibit_tracking_id;
											// $events_sess.leads.show_form__view_lead[$events_slct.exhibit_tracking_id] = true;
										}}
										class="btn btn-sm preset-tonal-primary flex flex-row justify-between items-center gap-0.5 min-w-72 lg:min-w-96 min-h-14 max-h-14"
									>
										<span class="fas fa-user mx-0.5"></span>
										<span class="text-lg grow text-center"
											>{event_exhibit_tracking_obj.event_badge_full_name}</span
										>
									</button>

									<span
										class="flex flex-col xl:flex-row gap-0.5 flex-wrap justify-between min-w-48 max-w-80"
									>
										<span class="text-sm min-w-56">
											<span class="fas fa-envelope mx-0.5"></span>
											<a
												href="mailto:{event_exhibit_tracking_obj.event_badge_email}"
												class="font-medium text-blue-600 dark:text-blue-500 hover:underline"
											>
												{event_exhibit_tracking_obj.event_badge_email}
											</a>
										</span>

										<span class="text-sm text-wrap min-w-56"
											>{event_exhibit_tracking_obj.event_badge_affiliations}</span
										>
									</span>
								</div>
							</td>
						</tr>
					{/each}
				</tbody>
			</table>
		{:else}
			No leads available to show
			{$lq__event_exhibit_tracking_obj_li}
		{/if}
	{:else}
		Loading...?
	{/if}
</section>

<!-- This block needs to be moved or something. It takes up too much space! -->
{#if $events_sess.leads.show_form__view_lead}
	<Leads_view_lead />
{/if}

<style lang="postcss">
	table.table > thead > tr > th {
		padding: 0.1em;
	}
	table.table > tbody > tr > td {
		padding: 0.1em;
	}

	/* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
	div.ae_quick_modal_container {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 100;
		background-color: hsla(0, 0%, 0%, 0.5);
	}

	/* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
	section.ae_quick_popover {
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 100;
		background-color: hsla(0, 0%, 100%, 0.95);
		padding: 1rem;
		border-radius: 0.5rem;
		box-shadow: 0 0 1rem hsla(0, 0%, 0%, 0.5);

		min-height: 98%;
		min-width: 98%;
	}

	section.ae_quick_popover_small {
		position: fixed;
		top: 1em;
		left: 50%;
		transform: translate(-50%, 0%);
		z-index: 100;
		background-color: hsla(0, 0%, 100%, 0.95);
		padding: 1rem;
		border-radius: 0.5rem;
		box-shadow: 0 0 1rem hsla(0, 0%, 0%, 0.5);

		min-hight: 24rem;
		max-height: 95%;
		min-width: 50%;
		max-width: 95%;
	}
</style>
