<script lang="ts">
	/** @type {import('./$types').PageData} */
	export let data: any;
	// console.log(`ae_core root +page.svelte data:`, data);

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

	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/element_ae_crud.svelte';
	// import Element_data_store from '$lib/element_data_store_v2.svelte';
	import Comp_person_obj_tbl from './ae_comp__person_obj_tbl.svelte';

	// import { liveQuery } from "dexie";
	import { core_func } from '$lib/ae_core/ae_core_functions';
	// import { db_core } from "$lib/db_core";
	// import { db_events } from "$lib/db_events";
	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';

	// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
	$slct.account_id = data.account_id;
	console.log(`$slct.account_id = `, $slct.account_id);
	let ae_acct = data[$slct.account_id];
	console.log(`ae_acct = `, ae_acct);

	let person_id_random_li: string[] = [];

	// let load_obj_li_results: Promise<any>|key_val;
	// let search_submit_results: Promise<any>|key_val;
</script>

<section class="ae_core md:container mx-auto">
	<h2 class="h3">Æ Core for {$ae_loc.account_name ?? 'Æ loading...'}</h2>

	<button
		type="button"
		on:click={() => {
			console.log('Edit the POC person for the session.');

			// let params = {
			//     qry__limit: $ae_loc.person.qry_limit__people,
			// }

			// $slct.person_obj_li = await core_func.load_ae_obj_li__person({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

			let person_results = core_func
				.load_ae_obj_li__person({
					api_cfg: $ae_api,
					for_obj_type: 'account',
					for_obj_id: $slct.account_id,
					limit: $ae_loc.person.qry_limit__people,
					// params: params,
					log_lvl: 1
				})
				.then(function (load_results) {
					console.log(`Loaded person_obj_li:`, load_results);

					// We need to make this ready for the select option list. Convert the list to a key value pair with the person_id_random as the key. We also need to set the option text value to: full_name (primary_email)
					if (load_results) {
						$slct.person_id_random_li = load_results;

						person_id_random_li = [];

						let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

						for (let i = 0; i < $slct.person_id_random_li.length; i++) {
							let person_obj = $slct.person_id_random_li[i];
							let person_id_random = person_obj.person_id_random;
							tmp_li.push(person_id_random);
						}
						person_id_random_li = tmp_li;

						// $slct.person_id_random_li = load_results.map((person_obj) => person_obj.person_id_random);
						// let person_obj_li = load_results;
						// let person_obj_kv = {};
						// person_obj_kv[''] = '-- Select a person --';
						// person_obj_li.forEach((person_obj) => {
						//     let option_text = `${person_obj.full_name} (${person_obj.primary_email})`;
						//     person_obj_kv[person_obj.person_id_random] = option_text;
						// });
						// $slct.person_obj_kv = person_obj_kv;
					}
					// $slct.person_obj_kv = $slct.person_obj_kv;
					// console.log(`$slct.person_obj_kv = `, $slct.person_obj_kv);

					return load_results;
				})
				.finally(() => {
					console.log(`person_id_random_li:`, person_id_random_li);
					$ae_sess.person.show_report__person_li = true;
				});
		}}
		class="btn btn-sm preset-tonal-warning hover:preset-tonal-warning border border-warning-500"
	>
		<span class="fas fa-user mx-1"></span>
		List People
	</button>

	<button
		type="button"
		on:click={async () => {
			console.log('Add Person');
			if (
				!confirm(
					`Add a new person to the account?\n${$ae_loc.account_name}\nID: ${$slct.account_id}`
				)
			) {
				return;
			}

			let person_data = {
				account_id_random: $slct.account_id,
				// user_id_random: user_obj.user_id_random,
				source_code: 'manual:SK-core',
				given_name: 'New',
				family_name: 'Person',
				// professional_title: 'Temp Prof Title',
				// affiliations: 'Temp Org',
				// primary_email: 'tmp+person@oneskyit.com',
				// allow_auth_key: false,
				auth_key: Math.floor(Math.random() * 90000000) + 10000000,
				// Random number between 100000 and 999999
				passcode: Math.floor(Math.random() * 900000) + 100000,
				enable: true
			};

			let new_person_obj = await core_func.create_ae_obj__person({
				api_cfg: $ae_api,
				// user_id: $ae_loc.user_id,
				data_kv: person_data,
				log_lvl: 1
			});

			console.log('new_person_obj:', new_person_obj);

			if (
				confirm(
					`Person created:\n${new_person_obj.full_name} (${new_person_obj.primary_email ?? 'no email'})\nID: ${new_person_obj.person_id_random}\n\nView this person?`
				)
			) {
				// window.location.reload();
				// invalidateAll();
				goto(`/core/person/${new_person_obj.person_id_random}`, { replaceState: true });
				// pushState(`/core/person/${new_person_obj.person_id_random}`, { replace: true });
				// replaceState(`/core/person/${new_person_obj.person_id_random}`);
			}
		}}
		class:hidden={!$ae_loc.edit_mode}
		class="btn btn-sm preset-tonal-warning hover:preset-filled-warning-500"
	>
		<span class="fas fa-plus mx-1"></span>
		Add Person
	</button>

	<!-- Show people for this account -->
	{#if $ae_sess.person.show_report__person_li && person_id_random_li?.length > 0}
		<h3 class="h4 text-center">Person Records</h3>

		<label class="text-sm" for="qry_limit__people"
			>Max results:

			<select
				id="qry_limit__people"
				bind:value={$ae_loc.person.qry_limit__people}
				on:change={() => {
					core_func
						.load_ae_obj_li__person({
							api_cfg: $ae_api,
							for_obj_type: 'account',
							for_obj_id: $slct.account_id,
							enabled: 'enabled',
							hidden: 'not_hidden',
							limit: $ae_loc.person.qry_limit__people,
							// params: {
							//     'qry__enabled': 'enabled',
							//     'qry__hidden': 'not_hidden',
							//     'qry__limit': $ae_loc.person.qry_limit__people,},
							log_lvl: 1
						})
						.then(function (load_results) {
							console.log(`Loaded person_obj_li:`, load_results);
							if (load_results) {
								$slct.person_id_random_li = load_results;

								person_id_random_li = [];

								let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.

								for (let i = 0; i < $slct.person_id_random_li.length; i++) {
									let person_obj = $slct.person_id_random_li[i];
									let person_id_random = person_obj.person_id_random;
									tmp_li.push(person_id_random);
								}
								person_id_random_li = tmp_li;
							}
							return load_results;
						});
				}}
				class="select max-w-20 text-sm"
			>
				<option value={25}>25</option>
				<option value={50}>50</option>
				<option value={75}>75</option>
				<option value={100}>100</option>
				<option value={150}>150</option>
				<option value={200}>200</option>
				<option value={250}>250</option>
				<option value={500}>500</option>
				<option value={750}>750</option>
				<option value={1000}>1000</option>
			</select>
		</label>

		<div class="outline">
			<!-- Count: {person_id_random_li?.length} -->
			<Comp_person_obj_tbl bind:person_id_random_li show_user_fields={$ae_loc.administrator_access}
			></Comp_person_obj_tbl>
		</div>
	{/if}
</section>
