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

let { data, children } = $props();

import { goto } from '$app/navigation';
import { BookHeart, FilePlus } from '@lucide/svelte';

import { liveQuery } from "dexie";

import { ae_util } from '$lib/ae_utils/ae_utils';
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';


// interface Props {
//     data: any;
// }

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


let ae_acct = data[$slct.account_id];
if (log_lvl) {
    console.log(`ae_acct = `, ae_acct);
}

$journals_slct.journal_id = ae_acct.slct.journal_id;

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;
}));

</script>


<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 border-gray-200 border-y-2 py-2">
    <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>

    {#if $journals_slct?.journal_entry_id}
    <a href="/journals/{$journals_slct?.journal_id}" class="novi_btn btn btn-secondary btn-sm
        variant-ghost-tertiary
        hover:variant-filled-tertiary
        transition
        ">
        <span class="fas fa-arrow-left m-1"></span>
        Back to Journal Entries
    </a>
    {/if}

    <!-- 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>


{@render children()}


</section>