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

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

import { goto } from '$app/navigation';
import { BookHeart, Check, FilePlus, Minus, Notebook, Pencil, Plus, X } from '@lucide/svelte';

import { liveQuery } from "dexie";
import { Modal } from 'flowbite-svelte';

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

    $journals_slct.journal_obj = results;
    console.log(`lq__journal_obj: results = `, results);

    return results;
}));


async function handle_update_journal() {
    if ($journals_slct.tmp_journal_obj.name && $journals_slct.tmp_journal_obj.type_code) {
        try {
            let data_kv = {
                // account: $slct.account_id,
                name: $journals_slct.tmp_journal_obj.name,
                type_code: $journals_slct.tmp_journal_obj.type_code,
                passcode: $journals_slct.tmp_journal_obj.passcode,
                passcode_timeout: $journals_slct.tmp_journal_obj.passcode_timeout,

                cfg_json: $journals_slct.tmp_journal_obj.cfg_json

            };
            journals_func.update_ae_obj__journal({
                api_cfg: $ae_api,
                journal_id: $lq__journal_obj?.journal_id ?? '',
                data_kv: data_kv,
                log_lvl: log_lvl
            }).then((results) => {
                console.log('Journal updated:', results);
                // $journals_slct.journal_id = results?.journal_id_random;
            }).catch((error) => {
                    console.error('Error updating journal:', error);
                    alert('Failed to update 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 updated:', result);
            // $journals_sess.show__modal_new__journal_obj = false;
            // goto(`/journals/${result.journal_id_random}`);
        } catch (error) {
            console.error('Error updating journal:', error);
            alert('Failed to update journal.');
        }
    } else {
        alert('Please provide both name and type for the journal.');
    }
}

</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 flex-wrap
        gap-1
        items-center justify-between
        border-gray-200 border-y-
        w-full
        py-2
        "
    >
    <a href="/journals"
        class="
            btn btn-sm
            variant-ghost-tertiary
            hover:variant-filled-tertiary
            transition
            "
        >
        <BookHeart class="mx-1" />
        <span class="hidden md:inline">
            View Other Journals
        </span>

    </a>

    {#if $journals_slct?.journal_entry_id}
    <a
        href="/journals/{$journals_slct?.journal_id}"
        class="
            btn btn-sm
            variant-ghost-tertiary
            hover:variant-filled-tertiary
            transition
            "
        >
        <Notebook />
        <span class="hidden md:inline">Back to</span>
        <span class="font-bold">
            {$lq__journal_obj?.name || 'Journal'}
        </span>
    </a>
    {:else}
    <!-- Edit Journal button. Creates a modal to edit the journal. -->
    <button
        type="button"
        onclick={() => {
            $journals_slct.tmp_journal_obj = {
                name: $lq__journal_obj?.name,
                type_code: $lq__journal_obj?.type_code,
                passcode: $lq__journal_obj?.passcode,
                passcode_timeout: $lq__journal_obj?.passcode_timeout,
                cfg_json: $lq__journal_obj?.cfg_json
            };
            $journals_sess.show__modal_edit__journal_obj = true;
        }}
        class:hidden={!$ae_loc.edit_mode}
        class="
            btn btn-sm
            variant-ghost-warning
            hover:variant-filled-warning
            transition
            "
        >
        <Pencil />
        Edit Journal
    </button>
    {/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
            type="button"
            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}`);
                });
            }}
            class="
                btn btn-sm
                variant-ghost-success
                hover:variant-filled-success
                transition
                "
            >
            <FilePlus class="mx-1" />
            <!-- <span class="fas fa-plus m-1"></span> -->
            <span class="hidden sm:inline">
                New Journal Entry
            </span>
        </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="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>


<!-- Modal for editing journal -->
{#if $journals_sess.show__modal_edit__journal_obj}
<Modal
    title="Edit Journal"
    bind:open={$journals_sess.show__modal_edit__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">Edit Journal</h3> -->
            <div class="py-4">
                <input type="text" placeholder="Journal Name" bind:value={$journals_slct.tmp_journal_obj.name} class="input input-bordered w-full mb-2" />
                <input type="text" placeholder="Journal Type" bind:value={$journals_slct.tmp_journal_obj.type_code} class="input input-bordered w-full mb-2" />

                <!-- input for passcode -->
                <input type="text" placeholder="Passcode" bind:value={$journals_slct.tmp_journal_obj.passcode} class="input input-bordered w-full mb-2" />

                <!-- input for passcode timeout -->
                <input type="number" placeholder="Passcode Timeout" bind:value={$journals_slct.tmp_journal_obj.passcode_timeout} class="input input-bordered w-full mb-2" />

                <!-- select option for journal type_code -->
                <span class="text-sm text-gray-500 hidden sm:inline">
                    Journal Type:
                </span>
                <select
                    class="btn btn-sm
                    variant-ghost-surface
                    hover:variant-filled-surface
                    transition
                    text-xs
                    "
                    bind:value={$journals_slct.tmp_journal_obj.type_code}
                    onchange={(event) => {
                        // Update the cfg_json with the selected journal type. Example cate
                        $journals_slct.tmp_journal_obj.type_code = event.target.value;
                        console.log('Selected journal type:', $journals_slct.tmp_journal_obj.type_code);
                    }}
                    title="Select a journal type"
                    >
                    <option value="">Select Journal Type</option>
                    {#each $journals_loc.journal.type_code_li as journal_type}
                        <option value={journal_type.code}>{journal_type.name}</option>
                    {/each}
                </select>

                <div>
                    <!-- inputs for customizable journal category list -->
                    <!-- each category has a code and name; need to be able to add and remove categories -->
                    <span class="text-sm text-gray-500 hidden sm:inline">
                        Journal Categories:
                    </span>
                    <div class="flex flex-col gap-1">
                        {#each $journals_slct.tmp_journal_obj.cfg_json.category_li as category, index}
                            <div class="flex flex-row items-center gap-1">
                                <input type="text" placeholder="Category Code" bind:value={$journals_slct.tmp_journal_obj.cfg_json.category_li[index].code} class="input input-bordered w-full" />
                                <input type="text" placeholder="Category Name" bind:value={$journals_slct.tmp_journal_obj.cfg_json.category_li[index].name} class="input input-bordered w-full" />
                                <button
                                    type="button"
                                    class="btn btn-sm variant-ghost-danger hover:variant-filled-danger transition"
                                    onclick={() => {
                                        $journals_slct.tmp_journal_obj.cfg_json.category_li.splice(index, 1);
                                        $journals_slct.tmp_journal_obj.cfg_json.category_li = $journals_slct.tmp_journal_obj.cfg_json.category_li;
                                    }}
                                    >
                                    <Minus />
                                    Remove
                                </button>
                            </div>
                        {/each}
                        <button
                            type="button"
                            onclick={() => {
                                $journals_slct.tmp_journal_obj.cfg_json.category_li.push({ code: '', name: '' });
                                $journals_slct.tmp_journal_obj.cfg_json.category_li = $journals_slct.tmp_journal_obj.cfg_json.category_li;
                            }}
                            class="btn btn-sm variant-ghost-success hover:variant-filled-success transition max-w-96"
                            >
                            <Plus />
                            Add Category
                        </button>
                    </div>
                </div>

                <!-- Select max height options (Tailwind CSS) -->
                <div>
                    <span class="text-sm text-gray-500 hidden sm:inline">
                        Journal Entry List Max Height:
                    </span>
                    <select
                        class="btn btn-sm variant-ghost-surface hover:variant-filled-surface transition text-xs w-full mb-2 max-w-96"
                        bind:value={$journals_slct.tmp_journal_obj.cfg_json.entry_li_max_height}
                        title="Select maximum height for journal entries in the list"
                        onchange={(event) => {
                            $journals_slct.tmp_journal_obj.cfg_json.entry_li_max_height = event.target.value;
                            console.log('Selected max height:', $journals_slct.tmp_journal_obj.cfg_json.entry_li_max_height);
                        }}
                        >
                        <option value="">Default (auto)</option>
                        <!-- <option value="none">None (no limit)</option> -->
                        <option value="max-h-8">Small (8)</option>
                        <option value="max-h-16">Medium (16)</option>
                        <option value="max-h-32">Large (32)</option>
                        <option value="max-h-96">Extra Large (96)</option>
                        <option value="max-h-full">Full (no limit)</option>

                    </select>
                </div>


                <!-- textarea for json_cfg editing -->
            </div>

            <div class="modal-action">
                <button
                    type="button"
                    onclick={handle_update_journal}
                    class="btn variant-ghost-warning hover:variant-filled-warning transition"
                    >
                    <Check />
                    Update
                </button>
                <button
                    type="button"
                    onclick={$journals_sess.show__modal_edit__journal_obj ?? false}
                    class="btn variant-ghost-surface hover:variant-filled-surface transition"
                    >
                    <X />
                    Cancel
                </button>
            </div>
        </div>
    </div>
</Modal>
{/if}
