<script lang="ts">
interface Props {
    log_lvl?: number;
    lq__journal_obj: any;
}

let {
    log_lvl = $bindable(0),
    lq__journal_obj,
}: Props = $props();


import {
        ArrowDown01, ArrowDown10, ArrowDownUp,
        BetweenVerticalEnd, BetweenVerticalStart,
        BookHeart, BookImage, Bookmark, BookOpenText, BriefcaseBusiness,
        Check, Copy,
        Expand, Eye, EyeOff,
        Flag, FlagOff, FilePlus, Fingerprint,
        Globe,
        Library,
        MessageSquareWarning, Minus,
        Notebook,
        Pencil, Plus,
        RemoveFormatting,
        SquareLibrary,
        Shapes, Share2, ShieldCheck, ShieldMinus, Siren, Skull,
        Tags, Target, ToggleLeft, ToggleRight, Trash2, TypeOutline,
        X
    } from '@lucide/svelte';

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';


// Trigger doing a search query for journal entries
$effect(async () => {
if ($journals_trig.journal_entry_qry) {
    $journals_trig.journal_entry_qry = false;

    if (log_lvl) {
        console.log(`Triggered: $journals_trig.journal_entry_qry: ${$journals_loc.qry__search_text}`);
    }

    // $journals_prom.load__journal_entry_obj_qry = journals_func.qry__journal_entry({
    $journals_prom.load__journal_entry_obj_li = await journals_func.qry__journal_entry({
        api_cfg: $ae_api,
        journal_id: $lq__journal_obj?.journal_id ?? '',
        qry_str: $journals_loc.qry__search_text,

        // qry_created_on: null,
        // qry_alert: null,
        // qry_priority: null,
        // qry_type: and_type,

        // enabled: $journals_loc.recovery_meetings.qry__enabled,
        // hidden: $journals_loc.recovery_meetings.qry__hidden,
        // order_by_li: $journals_loc.recovery_meetings.qry__order_by_li,
        // limit: $journals_loc.recovery_meetings.qry__limit,
        // try_cache: try_cache,
        log_lvl: log_lvl,
    });
    if ($journals_prom.load__journal_entry_obj_li.length) {
        $journals_sess.entry_li = $journals_prom.load__journal_entry_obj_li;

        $journals_sess = {
            ...$journals_sess }; // ensure session is updated

        // $journals_trig.journal_entry_li = true; // trigger the entry list to refresh
        // $journals_trig.journal_entry_li = $journals_prom.load__journal_entry_obj_li;
    } else {
        console.log('Clear the search results: no entries found for that query.');
        // $journals_sess.entry_li = [''];
        $journals_sess.entry_li = null;
        // $journals_trig.journal_entry_li = true;
        // alert('No journal entries found for that search query.');
        // $journals_sess = $journals_sess;
    }

    if (log_lvl) {
        console.log(`$journals_sess.entry_li = `, $journals_sess.entry_li);
    }
}
});

</script>




<!-- Search input form -->
<span class="flex flex-row flex-wrap items-center justify-center gap-1">
    <span class="text-sm text-gray-500 hidden lg:inline">
        Search:
    </span>
    <input
        disabled={false}
        type="text"
        placeholder="Search Journal Entries"
        bind:value={$journals_loc.qry__search_text}
        onkeyup={(event) => {
            if (event.key === 'Enter') {
                // $journals_loc.qry__search_text = event.target.value;
                $journals_trig.journal_entry_qry = true;
            }
        }}
        title={`Search for Entries in "${$lq__journal_obj?.name}. Press Enter to search.`}
        autocomplete="off"
        class="
            input input-sm input-bordered
            w-44 md:w-52
            text-sm
            "
        class:bg-red-200={$journals_sess.entry_li == null}
        class:dark:bg-red-800={$journals_sess.entry_li == null}
        />
    <!-- Clear search text button -->
    <button
        type="button"
        class:hidden={!$journals_loc.qry__search_text}
        onclick={() => {
            console.log(`TESTING - 1 - Cleared search query: ${$journals_loc.qry__search_text}`);
            $journals_loc.qry__search_text = '';
            console.log(`TESTING - 2 - Cleared search query: ${$journals_loc.qry__search_text}`);
            $journals_trig.journal_entry_qry = true;
        }}
        class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-100-900
            hover:preset-filled-tertiary-100-900
            transition-all
            "
        title="Clear search query text"
        >
        <RemoveFormatting size="1.25em" class="text-neutral-800/60 dark:text-neutral-50/60" />
        <span class="hidden md:inline">
            Clear
        </span>

        {#await $journals_prom.load__journal_entry_obj_li}
            <span class="text-sm text-gray-500 italic">
                Loading...
            </span>
        {:then load_result}
            {#if load_result === null}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
                    No entries found - null
                </span>
            {:else if load_result?.length === 0}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic font-semibold">
                    No entries found
                </span>
            {:else if $journals_sess.entry_li?.length === 0}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
                    Enter to search
                </span>
            {:else}
                <span class="text-xs text-gray-600/80 dark:text-gray-400/80 italic">
                    {load_result?.length ?? 0} found
                </span>
            {/if}
        {:catch error}
            <span class="text-xs text-red-600/80 dark:text-red-400/80 italic">
                Error loading entries.
            </span>
        {/await}
    </button>

</span>


<!-- 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 md:inline">
        Category:
    </span>
    <select
        class="
            btn btn-sm
            preset-tonal-tertiary
            preset-outlined-tertiary-100-900
            hover:preset-filled-tertiary-100-900
            transition-all
            "
        bind:value={$journals_loc.qry__category_code}
        onchange={(event) => {
            // WARNING: This will cause pages to reset if the journal entry list is being filtered by category. This is a bug that should be fixed.
            $journals_loc.qry__category_code = event.target.value;
            $journals_loc.filter__category_code = event.target.value;
            $journals_trig.journal_entry_li = true;
            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>