<script lang="ts">
	interface Props {
		person_id: string;
		display_mode?: string; // 'default', 'compact', 'minimal', 'launcher'
	}

	let { person_id, display_mode = 'default' }: Props = $props();

	console.log(`ae_core person_view.svelte`);

	import { liveQuery } from 'dexie';

	import type { key_val } from '$lib/stores/ae_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	// import { api } from '$lib/api';
	import Element_ae_crud from '$lib/elements/element_ae_crud.svelte';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';

	import { core_func } from '$lib/ae_core/ae_core_functions';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import { db_core } from '$lib/ae_core/db_core';
	// import { db_events } from "$lib/db_events";
	// import { events_loc, events_sess, events_slct, events_trigger } from '$lib/stores/ae_events_stores';
	// import { events_func } from '$lib/ae_events_functions';

	let ae_placeholder_li: key_val = {};
	let ae_promises: key_val = $state({}); // Promise<any>;
	let ae_tmp: key_val = $state({});
	ae_tmp.value__hide = null;

	let ae_triggers: key_val = $state({});

	console.log(`person_id:`, person_id);
	let lq__person_obj = $derived(
		liveQuery(async () => {
			let results = await db_core.person.get(person_id);
			return results;
		})
	);

	ae_tmp.value__data_json = null;
	$effect(() => {
		if ($lq__person_obj?.data_json && ae_tmp.value__data_json === null) {
			ae_tmp.value__data_json = JSON.stringify($lq__person_obj.data_json, null, 4);
			// ae_tmp.value__data_json = JSON.parse(JSON.stringify($lq__person_obj.data_json));
			// JSON.stringify(jsObj, null, 4);
		}
	});

	ae_tmp.valid__data_json = null;
	$effect(() => {
		if (ae_tmp.value__data_json && ae_tmp.value__data_json.length) {
			console.log(`ae_tmp.value__data_json.length:`, ae_tmp.value__data_json.length);

			try {
				JSON.parse(ae_tmp.value__data_json);
				ae_tmp.valid__data_json = true;
			} catch (e) {
				ae_tmp.valid__data_json = false;
				console.error(`JSON.parse error:`, e);
			}
		}
	});

	// let tmp_agree = false;
	// let tmp_opt_out: key_val = {
	//     audio: false,
	//     video: false,
	//     transcription_and_publication: false,
	//     publication_in_app: false
	// };
</script>

{#if $lq__person_obj}
	<h2 class="h3">
		Person Details for:<br />
		<strong>
			"{$lq__person_obj.full_name}"
		</strong>
	</h2>

	<ul class="space-y-2 px-4">
		<li class:hidden={!$ae_loc.trusted_access || !$ae_loc.edit_mode}>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'external_id'}
				field_type={'text'}
				field_value={$lq__person_obj.external_id}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={false}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-id-card"></span>
				External ID:
				<span class="font-bold">
					{@html $lq__person_obj.external_id ?? ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>
		<li class:hidden={!$ae_loc.trusted_access || !$ae_loc.edit_mode}>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'external_sys_id'}
				field_type={'text'}
				field_value={$lq__person_obj.external_sys_id}
				allow_null={false}
				hide_edit_btn={!$ae_loc.administrator_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={true}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-fingerprint"></span>
				External System ID:
				<span class="font-bold">
					{@html $lq__person_obj.external_sys_id ?? ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>

		<li>
			<span class="fas fa-user"></span>

			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'given_name'}
				field_type={'text'}
				field_value={$lq__person_obj.given_name}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={true}
				display_block_edit={false}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="font-bold">
					{@html $lq__person_obj.given_name ?? ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'family_name'}
				field_type={'text'}
				field_value={$lq__person_obj.family_name}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={true}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="font-bold">
					{@html $lq__person_obj.family_name ?? ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>
		<li>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'primary_email'}
				field_type={'email'}
				field_value={$lq__person_obj.primary_email}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={true}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-envelope"></span>
				<span class="font-bold">
					{#if $lq__person_obj.primary_email}
						<a
							href="mailto:{$lq__person_obj?.primary_email}"
							class="text-blue-500 underline hover:text-blue-800"
							title="Person's primary email address"
						>
							{@html $lq__person_obj.primary_email ?? 'email' + ae_snip.html__not_set}
						</a>
					{:else}
						email {@html ae_snip.html__not_set}
					{/if}
				</span>
			</Element_ae_crud>
		</li>
		<li>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'affiliations'}
				field_type={'text'}
				field_value={$lq__person_obj.affiliations}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={false}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-building"></span>
				<span class="font-bold">
					{@html $lq__person_obj.affiliations ?? 'affiliations' + ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>
		<li>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'professional_title'}
				field_type={'text'}
				field_value={$lq__person_obj.professional_title}
				allow_null={false}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={false}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-user-tag"></span>
				<span class="font-bold">
					{@html $lq__person_obj.professional_title && $lq__person_obj.professional_title.length
						? $lq__person_obj.professional_title
						: 'professional title' + ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>
		<li>
			<Element_ae_crud
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj.person_id_random}
				field_name={'passcode'}
				field_type={'text'}
				field_value={$lq__person_obj.passcode}
				allow_null={true}
				hide_edit_btn={!$ae_loc.trusted_access || !$ae_loc.edit_mode}
				outline_element={false}
				show_crud={false}
				display_inline={false}
				class_li={''}
				on:ae_crud_updated={(e) => {
					console.log(`ae_crud_updated:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				<span class="fas fa-user-secret"></span>
				Passcode:
				<span class="font-bold">
					{@html $lq__person_obj.passcode ?? 'passcode' + ae_snip.html__not_set}
				</span>
			</Element_ae_crud>
		</li>

		<li hidden={!$ae_loc.trusted_access}>
			<!-- Show/Hide -->
			<Element_ae_crud
				trigger_patch={ae_triggers.hide}
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj?.person_id_random}
				field_name={'hide'}
				field_type={'button'}
				field_value={ae_tmp.value__hide}
				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:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				{#if $ae_loc.trusted_access}
					{$lq__person_obj?.hide ? 'Hidden' : 'Not Hidden'}
				{/if}
				<button
					onclick={() => {
						ae_tmp.value__hide = !$lq__person_obj?.hide;

						// $events_slct.exhibit_tracking_obj.hide = !$lq__person_obj?.hide;
						ae_triggers.hide = true;
					}}
					class="btn btn-sm preset-tonal-warning"
				>
					{#if $ae_loc.trusted_access}
						{@html $lq__person_obj?.hide
							? '<span class="fas fa-eye m-1"></span> Unhide?'
							: '<span class="fas fa-eye-slash m-1"></span> Hide?'}
					{:else}
						<!-- Users see this as the "Archive" option button -->
						{@html $lq__person_obj?.hide
							? '<span class="fas fa-archive m-1"></span> Unarchive'
							: '<span class="fas fa-archive m-1"></span> Archive'}
					{/if}
				</button>
			</Element_ae_crud>

			<!-- Enable/Disable -->
			<Element_ae_crud
				trigger_patch={ae_triggers.enable}
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj?.person_id_random}
				field_name={'enable'}
				field_type={'button'}
				field_value={ae_tmp.value__enable}
				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:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				{#if $ae_loc.trusted_access}
					{$lq__person_obj?.enable ? 'Enabled' : 'Disabled'}
				{/if}
				<button
					onclick={() => {
						ae_tmp.value__enable = !$lq__person_obj?.enable;

						// $events_slct.exhibit_tracking_obj.hide = !$lq__person_obj?.hide;
						ae_triggers.enable = true;
					}}
					class="btn btn-sm preset-tonal-warning"
				>
					{#if $ae_loc.trusted_access}
						{@html $lq__person_obj?.enable
							? '<span class="fas fa-toggle-on m-1"></span> Disable?'
							: '<span class="fas fa-toggle-off m-1"></span> Enable?'}
					{:else}
						<!-- Users see this as the "Archive" option button -->
						{@html $lq__person_obj?.enable
							? '<span class="fas fa-toggle-on m-1"></span> Disable'
							: '<span class="fas fa-toggle-off m-1"></span> Enable'}
					{/if}
				</button>
			</Element_ae_crud>

			<!-- Priority/Not -->
			<Element_ae_crud
				trigger_patch={ae_triggers.priority}
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj?.person_id_random}
				field_name={'priority'}
				field_type={'button'}
				field_value={ae_tmp.value__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:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				{#if $ae_loc.trusted_access}
					{$lq__person_obj?.priority ? 'Priority' : 'Not Priority'}
				{/if}
				<button
					onclick={() => {
						ae_tmp.value__priority = !$lq__person_obj?.priority;

						// $events_slct.exhibit_tracking_obj.hide = !$lq__person_obj?.hide;
						ae_triggers.priority = true;
					}}
					class="btn btn-sm preset-tonal-warning"
				>
					{#if $ae_loc.trusted_access}
						{@html $lq__person_obj?.priority
							? '<span class="fas fa-star m-1"></span> Not Priority?'
							: '<span class="fas fa-star m-1"></span> Priority?'}
					{:else}
						<!-- Users see this as the "Archive" option button -->
						{@html $lq__person_obj?.priority
							? '<span class="fas fa-star m-1"></span> Not Priority'
							: '<span class="fas fa-star m-1"></span> Priority'}
					{/if}
				</button>
			</Element_ae_crud>

			<!-- Allow Auth Key/Not -->
			<Element_ae_crud
				trigger_patch={ae_triggers.allow_auth_key}
				api_cfg={$ae_api}
				object_type={'person'}
				object_id={$lq__person_obj?.person_id_random}
				field_name={'allow_auth_key'}
				field_type={'button'}
				field_value={ae_tmp.value__allow_auth_key}
				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:`, e.detail);

					core_func
						.load_ae_obj_id__person({
							api_cfg: $ae_api,
							person_id: $lq__person_obj?.person_id_random,
							log_lvl: 1
						})
						.then(function (load_results) {
							// Maybe reload page?
							// window.location.reload();
						});
				}}
			>
				{#if $ae_loc.trusted_access}
					{$lq__person_obj?.allow_auth_key ? 'Allow Auth Key' : 'Not Allow Auth Key'}
				{/if}
				<button
					onclick={() => {
						ae_tmp.value__allow_auth_key = !$lq__person_obj?.allow_auth_key;

						// $events_slct.exhibit_tracking_obj.hide = !$lq__person_obj?.hide;
						ae_triggers.allow_auth_key = true;
					}}
					class="btn btn-sm preset-tonal-warning"
				>
					{#if $ae_loc.trusted_access}
						{@html $lq__person_obj?.allow_auth_key
							? '<span class="fas fa-key m-1"></span> Not Allow Auth Key?'
							: '<span class="fas fa-key m-1"></span> Allow Auth Key?'}
					{:else}
						<!-- Users see this as the "Archive" option button -->
						{@html $lq__person_obj?.allow_auth_key
							? '<span class="fas fa-key m-1"></span> Not Allow Auth Key'
							: '<span class="fas fa-key m-1"></span> Allow Auth Key'}
					{/if}
				</button>
			</Element_ae_crud>
		</li>

		<li>
			<div class="label person__data_json space-y-4">
				<label for="person__data_json" class="label">
					<span class="fas fa-book"></span>
					Person JSON Data
					<span class="text-sm text-gray-500"> (no character limit) </span>
				</label>

				<textarea
					name="data_json"
					id="person__data_json"
					disabled={!$ae_loc.administrator_access}
					class="textarea ae_value person__data_json font-mono"
					class:preset-tonal-error={ae_tmp.value__data_json && ae_tmp.value__data_json.length > 600
						? true
						: false}
					required
					rows="8"
					cols="70"
					bind:value={ae_tmp.value__data_json}
					placeholder="Enter data_json here"
				></textarea>
				<!-- {/if} -->
			</div>

			<p>
				JSON length: {ae_tmp.value__data_json
					? ae_util.number_w_commas(ae_tmp.value__data_json.length)
					: 0} characters

				{#if ae_tmp.valid__data_json}
					<span class="fas fa-check text-green-500"></span>
				{:else}
					<span class="fas fa-exclamation-triangle text-red-500"></span>
					Invalid JSON
				{/if}
			</p>

			<div class="flex flex-wrap gap-2 p-1">
				<button
					type="button"
					class="btn btn-md preset-tonal-primary hover:preset-filled-primary-500"
					disabled={!$ae_loc.trusted_access || ae_tmp.value__data_json == $lq__person_obj.data_json}
					onclick={() => {
						console.log('*** Save button clicked ***');

						// We need to parse the JSON string into an object. In the future this should be dynamic and allow for basic key_val object.
						let data_json_obj = JSON.parse(ae_tmp.value__data_json);

						let person_data = {
							data_json: data_json_obj
						};

						ae_promises.update__person_obj = core_func
							.update_ae_obj__person({
								api_cfg: $ae_api,
								person_id: $lq__person_obj.person_id_random,
								data_kv: person_data,
								log_lvl: 0
							})
							.then(function (update_result) {
								// console.log(update_result);
								// return update_result;
							});
					}}
				>
					{#await ae_promises.update__person_obj}
						<span class="fas fa-spinner fa-spin mx-1"></span>
					{:then}
						{#if ae_tmp.value__data_json == $lq__person_obj.data_json}
							<span class="fas fa-check mx-1"></span>
						{:else}
							<span class="fas fa-save mx-1"></span>
						{/if}
					{/await}
					Save JSON
				</button>
			</div>
		</li>
	</ul>
{/if}
