<script lang="ts">
	let log_lvl: number = 0;
	// console.log(`ae_journals +page data:`, data);
	// console.log(`ae_journals Data Params:`, data.url.searchParams.get('journal_id'));

	// *** Import Svelte specific
	import { onMount } from 'svelte';
	import { goto } from '$app/navigation';

	// *** Import other supporting libraries
	import { BookPlus, FolderPlus, Library, SquareLibrary, Wrench } from '@lucide/svelte';
	import { liveQuery } from 'dexie';
	import { Modal } from 'flowbite-svelte';

	// *** Import Aether specific variables and functions
	// import { api } from '$lib/api';
	import { db_journals } from '$lib/ae_journals/db_journals';
	import { journals_func } from '$lib/ae_journals/ae_journals_functions';
	import { ae_loc, ae_sess, ae_api, slct, slct_trigger } from '$lib/stores/ae_stores';
	import {
		journals_loc,
		journals_sess,
		journals_slct,
		journals_trig
	} from '$lib/ae_journals/ae_journals_stores';
	import { ae_util } from '$lib/ae_utils/ae_utils';
	interface Props {
		data: any;
	}

	let { data }: Props = $props();

	import Modal_journals_cfg from './modal_journals_config.svelte';
	import Journal_obj_li from './ae_comp__journal_obj_li.svelte';

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

	let ae_acct = data[$slct.account_id];
	// $journals_slct.journal_obj = ae_acct.slct.journal_obj;
	// $journals_slct.journal_obj_li = ae_acct.slct.journal_obj_li;

	let lq__journal_obj_li = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal
				.where('person_id')
				.equals($ae_loc.person_id)
				// .sortBy('group')
				// .sortBy('priority')
				// .sortBy('sort')
				.reverse()
				.sortBy('tmp_sort_3');

			// .orderBy('tmp_sort_3')
			// .reverse()
			// .toArray()

			// .sortBy('start_datetime')
			// () => db_journals.journals
			//     .where('conference')
			//     // .aboveOrEqual(0)
			//     .equals('true')
			//     // .above(0)
			//     .sortBy('name') // Use sortBy() instead of orderBy(). toArray() is also not needed???
			//     // .sortBy('[priority+name]')
			//     // .orderBy('name')
			//     // .offset(10).limit(5)
			//     // .toArray()

			return results;
		})
	);
	// console.log(`lq__journal_obj_li:`, $lq__journal_obj_li);

	let lq__journal_obj = $derived(
		liveQuery(async () => {
			let results = await db_journals.journal.where('id').equals(ae_acct.slct.journal_id).toArray();
			// .first()
			// .get($journals_slct.journal_id)

			return results;
		})
	);

	onMount(() => {
		console.log('Journals: +page.svelte');

		console.log('ae_ slct:', $slct);

		let href_url = window.location.href;
		// console.log(href_url);

		$ae_loc.href_url = href_url;
		console.log(`lq__journal_obj = `, $lq__journal_obj);
	});

	async function create_journal() {
		// Confirm before creating a new journal
		if (confirm('Are you sure you want to create a new journal?')) {
			console.log('Creating new journal...');
		} else {
			console.log('Journal creation cancelled.');
			return;
		}

		if ($journals_sess.journal.new_journal_name && $journals_sess.journal.new_journal_type_code) {
			$journals_slct.journal_id = null;
			try {
				let data_kv = {
					// account: $slct.account_id,
					person_id_random: $ae_loc.person_id,
					name: $journals_sess.journal.new_journal_name,
					type_code: $journals_sess.journal.new_journal_type_code,
					cfg_json: {
						category_li: [{ code: '', name: 'Default' }]
					}
				};
				journals_func
					.create_ae_obj__journal({
						api_cfg: $ae_api,
						account_id: $slct.account_id,
						data_kv: data_kv,
						log_lvl: log_lvl
					})
					.then((results) => {
						console.log('New journal created:', results);
						$journals_slct.journal_id = results?.journal_id_random;
					})
					.catch((error) => {
						console.error('Error creating journal:', error);
						alert('Failed to create journal.');
					})
					.finally(() => {
						if ($journals_slct.journal_id) {
							$journals_sess.show__modal_new__journal_obj = false;
							goto(`/journals/${$journals_slct.journal_id}`);
						}
					});
				// console.log('New journal created:', result);
				// $journals_sess.show__modal_new__journal_obj = false;
				// goto(`/journals/${result.journal_id_random}`);
			} catch (error) {
				console.error('Error creating journal:', error);
				alert('Failed to create journal.');
			}
		} else {
			alert('Please provide both name and type for the journal.');
		}
	}
</script>

<!-- Svelte Page for a AE Journals Module main page -->
<section
	class="
    ae_journals
    mx-auto
    flex flex-col gap-1
    items-center
    min-h-full
    max-h-max
    min-w-full
    max-w-max
    space-y-2
    "
>
	<h1 class="h1 text-4xl text-center text-gray-800 dark:text-gray-200">
		<!-- <Library size="1em" class="mx-1 inline-block" /> -->
		<SquareLibrary size="1em" class="mx-1 inline-block text-neutral-800/60" />
		Journals for {$ae_loc.account_name ?? 'Æ loading...'}
		{$ae_loc.person.given_name ? `- ${$ae_loc.person.given_name}` : ''}
	</h1>

	<div
		class="flex flex-row flex-wrap gap-1 items-center justify-center w-full border-gray-200 border-y-2 py-2"
		class:hidden={!$ae_loc.edit_mode}
	>
		<!-- Add new journal button -->
		<button
			type="button"
			class="
            btn btn-sm
            preset-tonal-secondary border border-secondary-500
            hover:preset-filled-secondary-500
            transition
            "
			onclick={() => {
				$journals_sess.show__modal_new__journal_obj = true;
			}}
			title="Create a new journal"
		>
			<!-- <FolderPlus class="mx-1" /> -->
			<BookPlus class="mx-1" />
			<span class="hidden md:inline"> New Journal </span>
		</button>

		<!-- Show Journals Config button -->
		<button
			type="button"
			class="
            btn btn-sm
            preset-tonal-secondary border border-secondary-500
            hover:preset-filled-secondary-500
            transition
            "
			onclick={() => {
				$journals_sess.show__modal__journals_config = true;
				// Redirect to the journals config page
				// goto('/journals/config');
			}}
			title="Configure Journals"
		>
			<Wrench class="mx-1" />
			<span class="hidden md:inline"> Journals Config </span>
		</button>
	</div>

	<!-- <Element_data_store
    ds_code="journals___overview"
    ds_type="html"
    for_type="journal"
    for_id={$journals_slct.journal_id}
    display="block"
    class_li="p-2"
    /> -->

	<!-- <Element_data_store
    ds_code="journals___example"
    ds_type="html"
    for_type="journal"
    for_id={$journals_slct.journal_id}
    ds_name="Default: Journals - Journals Example"
    store="local"
    display="block"
    class_li="variant-ghost-surface p-2"
    try_cache={true}
    show_edit={false}
    /> -->

	{#await ae_acct.slct.journal_obj_li}
		<div class="flex flex-col items-center justify-center p-8">
			<span class="fas fa-spinner fa-spin text-4xl text-primary-500 mb-4"></span>
			<span class="text-lg text-gray-600 dark:text-gray-400">Loading journals...</span>
		</div>
	{:then}
		<!-- <span class="flex flex-row items-center justify-center">
    <span class="fas fa-check text-green-500 mx-1"></span>
    <span>Loaded</span>
</span> -->

		{#if $lq__journal_obj_li && $lq__journal_obj_li?.length}
			<Journal_obj_li {lq__journal_obj_li} />
		{:else}
			<div class="flex flex-col items-center justify-center p-4 text-center">
				<p class="text-lg text-gray-600 dark:text-gray-400 mb-4">No journals found.</p>
				<p class="text-md text-gray-500 dark:text-gray-300">
					Click the "New Journal" button above to create your first journal.
				</p>
			</div>
		{/if}
	{:catch error}
		<div class="text-red-800">
			<span class="fas fa-exclamation-triangle text-xl"></span>
			<span>Error: {error.message}</span>
		</div>
	{/await}
</section>

<!-- Modal for creating new journal -->
{#if $journals_sess.show__modal_new__journal_obj}
	<Modal
		title="Create New Journal"
		bind:open={$journals_sess.show__modal_new__journal_obj}
		autoclose={false}
		placement="top-center"
		size="xl"
		class="top-center bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 rounded-lg border-gray-200 dark:border-gray-700 divide-gray-200 dark:divide-gray-700 shadow-md relative flex flex-col mx-auto w-full divide-y"
	>
		<div class="modal">
			<div class="modal-box">
				<h3 class="font-bold text-lg">Create New Journal</h3>
				<div class="py-4">
					<input
						type="text"
						placeholder="Journal Name"
						bind:value={$journals_sess.journal.new_journal_name}
						class="input input-bordered w-full mb-2"
					/>
					<input
						type="text"
						placeholder="Journal Type"
						bind:value={$journals_sess.journal.new_journal_type_code}
						class="input input-bordered w-full mb-2"
					/>
				</div>
				<div class="modal-action">
					<button class="btn preset-tonal-primary" onclick={create_journal}>Create</button>
					<button
						type="button"
						onclick={() => {
							// Close the modal
							$journals_sess.show__modal_new__journal_obj = false;
						}}
						class="btn preset-tonal-secondary"
					>
						Cancel
					</button>
				</div>
			</div>
		</div>
	</Modal>
{/if}

{#if $journals_sess.show__modal__journals_config}
	<Modal_journals_cfg show={$journals_sess.show__modal__journals_config} />
{/if}

<style lang="postcss">
</style>
