<script lang="ts">
/** @type {import('./$types').PageData} */
let log_lvl: number = 0;

// *** Import Svelte specific
import { browser } from '$app/environment';
import { goto } from '$app/navigation';

import { BookHeart, FilePlus } from '@lucide/svelte';

// *** Import other supporting libraries
import { Modal } from 'flowbite-svelte';
import { liveQuery } from "dexie";

// *** Import Aether specific variables and functions
// import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
// import { core_func } from '$lib/ae_core/ae_core_functions';
import { db_journals } from "$lib/ae_journals/db_journals";
import { ae_snip, ae_loc, ae_sess, ae_api, ae_trig, slct, slct_trigger } from '$lib/ae_stores';
import { journals_loc, journals_sess, journals_slct, journals_prom, journals_trig } from '$lib/ae_journals/ae_journals_stores';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';

// import Journal_obj_id_edit from './ae_journals_comp__journal_obj_id_edit.svelte';
import Journal_view from './../ae_comp__journal_obj_id_view.svelte';
// import Journal_page_menu from './session_page_menu.svelte';
// import Element_data_store from '$lib/element_data_store_v2.svelte';

import Journal_entry_obj_li from './../ae_comp__journal_entry_obj_li.svelte';
// import Journal_entry_obj_id_edit from './ae_journals_comp__journal_entry_obj_id_edit.svelte';

interface Props {
    data: any;
}

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

// let ae_promises: key_val = {};
// let ae_tmp: key_val = {};
// let ae_triggers: key_val = {};

// Variables
// *** Quickly pull out data from parent(s)
let ae_acct = data[$slct.account_id];
if (log_lvl) {
    console.log(`ae_acct = `, ae_acct);
}

// For some reason data.params.journal_id (or whatever param) is not being passed to this page when loaded by a link from another page. This seems to be a bug with Svelte or SvelteKit. Hopefully fixed in a future version 5? 2024-11-06
$journals_slct.journal_id = ae_acct.slct.journal_id;
// $journals_slct.journal_obj = ae_acct.slct.journal_obj;


let lq__journal_obj = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`lq__journal_obj: journal_id = ${$journals_slct?.journal_id}`);
    }
    let results = await db_journals.journal
        .get($journals_slct?.journal_id ?? ''); // null or undefined does not reset things like '' does
    console.log(`lq__journal_obj: results = `, results);

    return results;
}));


let lq__journal_entry_obj_li = $derived(liveQuery(async () => {
    if (log_lvl) {
        console.log(`$lq__journal_obj.cfg_json = `, $lq__journal_obj?.cfg_json);
        console.log(`$journals_loc.filter__category_code = `, $journals_loc.filter__category_code);
    }
    if ($lq__journal_obj?.cfg_json?.entry_group_sort === 'DESC') {
        let results = await db_journals.journal_entry
            // .orderBy('updated_on')
            .where('journal_id')
            .equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
            .reverse()
            // .sortBy('tmp_sort_2');
            .sortBy('updated_on');
            // .sortBy('title');

        return results;
    } else if ($journals_loc.filter__category_code && $journals_loc.filter__category_code.length > 0) {
        console.log(`lq__journal_entry_obj_li - filtering by category_code: ${$journals_loc.filter__category_code}`);
        let results = await db_journals.journal_entry
            .where('journal_id')
            .equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
            .and(entry => entry.category_code === $journals_loc.filter__category_code)
            .reverse()
            .sortBy('tmp_sort_1');

        return results;
    } else {
        console.log(`lq__journal_entry_obj_li - default query using journal_id: ${$journals_slct?.journal_id}`);
        let results = await db_journals.journal_entry
            .where('journal_id')
            .equals($journals_slct?.journal_id ?? '') // null or undefined does not reset things like '' does
            .reverse()
            .sortBy('tmp_sort_1');
            // .sortBy('updated_on');

        return results;
    }

}));


$effect(() => {
if ($journals_trig.journal_entry_li) {
    $journals_trig.journal_entry_li = false;

    if (log_lvl) {
        console.log(`Triggered: $journals_trig.journal_entry_li`);
    }

    if ($journals_loc.qry__enabled !== 'all' || $journals_loc.qry__hidden !== 'all') {
        console.log(`Not set to all for enabled or hidden. Clearing all  journal entries to be safe.`);

        let results = db_journals.journal_entry
            .clear();
        console.log(`Deleted ${results} disabled journal entry.`);

    }

    $journals_prom.load__journal_entry_obj_li = journals_func.load_ae_obj_li__journal_entry({
        api_cfg: $ae_api,
        for_obj_type: 'journal',
        for_obj_id: $journals_slct.journal_id,
        enabled: $journals_loc.qry__enabled,
        hidden: $journals_loc.qry__hidden,
        limit: $journals_loc.qry__limit,
        order_by_li: $journals_loc.qry__order_by_li,
        try_cache: true,
        log_lvl: log_lvl,
    });
}
});

if (browser) {
    console.log('Browser environment detected.');

    let message = {'journal_id': $journals_slct?.journal_id ?? null};
    window.parent.postMessage(message, "*");
}

</script>


<svelte:head>
	<title>
        &AElig; Journals:
        {$lq__journal_obj?.name ? ae_util.shorten_string({ string: $lq__journal_obj?.name, max_length: 20, begin_length: 10, end_length: 4 }) : ''}
        - {$ae_loc?.title}
    </title>
</svelte:head>


<section
    class="
        ae_journals__journal
        container h-full mx-auto
        flex flex-col gap-1
        py-1 px-2 pb-16
        items-center
        min-w-full
        max-w-max
        "
    >


<div class="flex flex-row items-center justify-between w-full">
    <a href="/journals"
        class="btn btn-sm
        variant-ghost-tertiary
        hover:variant-filled-tertiary
        transition
        ">
        <!-- <span class="fas fa-arrow-left m-1"></span> Back to Journals -->
        <!-- <span class="fas fa-arrow-left m-1"></span> -->
        <BookHeart class="mx-1" />
        View Other Journals
    </a>

    <!-- Add default journal entry -->
    <span class="flex flex-row items-center gap-1">
        <span class="text-sm text-gray-500 hidden md:inline">
            New entry:
        </span>
        <button
            class="
            btn btn-sm
            variant-ghost-success
            hover:variant-filled-success
            transition
            "
            onclick={() => {
                // $journals_sess.show__modal_new__journal_entry_obj = true;

                let data_kv = {
                    category_code: null,
                };
                if ($journals_loc.qry__category_code) {
                    data_kv.category_code = $journals_loc.qry__category_code;
                }
                if (log_lvl) {
                    console.log('Creating new journal entry with data_kv:', data_kv);
                }
                journals_func.create_ae_obj__journal_entry({
                    api_cfg: $ae_api,
                    journal_id: $lq__journal_obj?.journal_id,
                    data_kv: data_kv,
                    log_lvl: log_lvl
                }).then((results) => {
                    console.log('New journal entry created:', results);
                    $journals_slct.journal_entry_id = results?.journal_entry_id_random;
                    // alert(`Journal entry created successfully! ${$journals_slct.journal_entry_id}`);
                }).catch((error) => {
                    console.error('Error updating journal entry:', error);
                    alert('Failed to update journal entry.');
                }).finally(() => {
                    goto(`/journals/${$lq__journal_obj?.journal_id}/entry/${$journals_slct.journal_entry_id}`);
                });
            }}
            >
            <FilePlus class="mx-1" />
            <!-- <span class="fas fa-plus m-1"></span> -->
            New Journal Entry
        </button>

        <!-- Give list of categories to base the new entry on -->
        <span class="flex flex-row items-center gap-2">
            <span class="text-sm text-gray-500 hidden sm:inline">
                Category:
            </span>
            <select
                class="novi_btn btn btn-secondary btn-sm
                variant-soft-primary
                hover:variant-filled-primary
                transition
                text-xs
                "
                bind:value={$journals_loc.qry__category_code}
                onchange={(event) => {
                    $journals_loc.qry__category_code = event.target.value;
                    console.log('Selected category:', $journals_loc.qry__category_code);
                }}
                title="Select a category for the new journal entry"
                >
                <option value="">Select Category</option>
                {#each $lq__journal_obj?.cfg_json.category_li as category}
                    <option value={category.code}>{category.name}</option>
                {/each}
            </select>
        </span>
    </span>

</div>

<Journal_view
    lq__journal_obj={lq__journal_obj}
    lq__journal_entry_obj_li={lq__journal_entry_obj_li}
    />

{#if $lq__journal_entry_obj_li && $lq__journal_entry_obj_li?.length }
    <Journal_entry_obj_li
        lq__journal_entry_obj_li={lq__journal_entry_obj_li}
        />
{:else}
    <p>No journal entry available to show.</p>
{/if}


</section>


<!-- Modal: Journal edit ID -->
<Modal
    title="{$lq__journal_obj?.name} - {$lq__journal_obj?.id}"
    bind:open={$journals_sess.show__modal_edit__journal_id}
    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"
    >

    {#snippet header()}

            <div class="flex flex-row items-center justify-between w-full">
                <h3 class="text-lg font-semibold">
                {#if $ae_loc.trusted_access}
                <!-- <div class="ae_options"> -->
                    <button
                        type="button"
                        onclick={() => {
                        // const url = new URL(location);
                        // url.searchParams.set('event_id', $lq__journal_obj?.event_id_random);
                        // history.pushState({}, '', url);

                        $journals_sess.show__modal_view__journal_id = $journals_slct.journal_id;
                        $journals_sess.show__modal_edit__journal_id = false;
                    }}
                        class="novi_btn btn btn-sm variant-ghost-warning hover:variant-filled-warning transition"
                        title={`View meeting: ${$lq__journal_obj?.name}`}
                        >
                        <span class="fas fa-eye m-1"></span> View
                    </button>
                <!-- </div> -->
                {/if}

                <span class="text-sm text-gray-500">
                    Edit Journal:
                </span>
                {$lq__journal_obj?.name}
            </h3>
            </div>


    {/snippet}

    <!-- <Journal_obj_id_edit
        lq__journal_obj={lq__journal_obj}
        /> -->


    <!-- <svelte:fragment slot="footer">
        <div class="text-center w-full">
            <button
                type="button"
                on:click={() => {
                    console.log('Close modal');
                    $journals_sess.recovery_meetings.show__modal_edit__journal_id = false;
                }}
                class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                >
                <span class="fas fa-times mx-1"></span>
                Close
            </button>
        </div>
    </svelte:fragment> -->

</Modal>


<!-- Modal: Journal Entry new -->
<Modal
    bind:open={$journals_sess.show__modal_new__journal_entry_obj}
    title="New Journal Entry - {$lq__journal_obj?.name}"
    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"
    >

    {#snippet header()}

            <div class="flex flex-row items-center justify-between w-full">
                <h3 class="text-lg font-semibold">
                    <button
                        type="button"
                        onclick={() => {
                            // Cancel the new journal entry
                            $journals_sess.show__modal_new__journal_entry_obj = false;
                            $journals_slct.journal_entry_id = null;
                            $journals_slct.journal_entry_obj = null;
                        }}
                        class="novi_btn btn btn-sm variant-ghost-warning hover:variant-filled-warning transition"
                        title={`Cancel new journal entry`}
                        >
                        <span class="fas fa-times m-1"></span> Cancel
                    </button>
                    New Journal Entry
                    <span class="text-sm text-gray-500">
                        {$lq__journal_obj?.name}
                    </span>
                </h3>
            </div>

    {/snippet}



</Modal>


<!-- Modal: Journal Content ID media player -->
<!-- {#if $journals_slct.journal_entry_id && $journals_sess.show__modal_view__journal_entry_id}
    <Modal_media_player
        lq__journal_entry_obj={lq__journal_entry_obj}
        />
{/if} -->
