<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
    } 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/ae_stores';
import { journals_loc, 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 Journal_obj_li from './ae_comp__journal_obj_li.svelte';
	import { journals_sess } from '$lib/ae_journals/ae_journals_stores';

// 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
    .orderBy('updated_on')
    .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,
                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-center">
    <!-- <Library size="1em" class="mx-1 inline-block" /> -->
    <SquareLibrary size="1em" class="mx-1 inline-block text-gray-500"/>
    Journals for {$ae_loc.account_name ?? 'Æ loading...'}
</h1>

<div class="flex flex-row items-center justify-center w-full border-gray-200 border-y-2 py-2">
    <!-- Add new journal button -->
    <button
        class="
        btn btn-sm
        variant-ghost-secondary
        hover:variant-filled-secondary
        transition
        "
        onclick={
            () => {
                $journals_sess.show__modal_new__journal_obj = true;
            }
        }
        >
        <!-- <FolderPlus class="mx-1" /> -->
        <BookPlus />
        New Journal
    </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-row items-center justify-center">
    <span class="fas fa-spinner fa-spin mx-1"></span>
    <span>Loading data...</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={lq__journal_obj_li}
    />
{:else}
    <p>No journals available to show.</p>
{/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 variant-glass-primary"
                onclick={create_journal}>Create</button>
            <button
                type="button"
                onclick={() => {
                    // Close the modal
                    $journals_sess.show__modal_new__journal_obj = false;
                }}
                class="btn variant-glass-secondary"
            >
                Cancel
            </button>
        </div>
    </div>
</div>

</Modal>
{/if}


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