<script lang="ts">
// *** Import Svelte specific

import {
    ArrowDown01,
    ArrowDown10,
    ArrowDownUp,
    BookHeart,
    BriefcaseBusiness,
    CalendarClock,
    CalendarOff,
    Clock,
    CodeXml,
    Copy,
    Eye,
    EyeOff,
    Flag,
    FlagOff,
    FileX,
    FingerprintPattern,
    Globe,
    Group,
    History,
    LockKeyhole,
    LockKeyholeOpen,
    MessageSquareWarning,
    Minus,
    NotebookPen,
    NotebookText,
    NotepadTextDashed,
    Pencil,
    PenLine,
    Plus,
    RemoveFormatting,
    Search,
    Shapes,
    Share2,
    ShieldCheck,
    ShieldMinus,
    Siren,
    Skull,
    SquareLibrary,
    Tags,
    Trash2,
    TypeOutline,
    X
} from '@lucide/svelte';

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';
import { journals_slct } from '$lib/ae_journals/ae_journals_stores';
import { goto } from '$app/navigation';

interface Props {
    log_lvl?: number;
    obj_priority: any;
    obj_sort: any;
    obj_group: any;
    obj_archive_on: any;
    obj_hide: any;
    obj_enable: any;
    obj_delete: any;
    tmp_entry_obj: any;
    update_journal_entry: any;
    lq__journal_entry_obj: any;
    change_journal_id: any;
    lq__journal_obj_li: any;
}

let {
    log_lvl = 0,
    obj_priority,
    obj_sort,
    obj_group,
    obj_archive_on,
    obj_hide,
    obj_enable,
    obj_delete,
    tmp_entry_obj,
    update_journal_entry,
    lq__journal_entry_obj,
    change_journal_id,
    lq__journal_obj_li
}: Props = $props();

let ae_promises: key_val = $state({});
</script>

<section
    class="ae_meta flex w-full flex-row flex-wrap items-center justify-between gap-1">
    <!-- {lq__journal_entry_obj?.priority}
{lq__journal_entry_obj?.sort}
{lq__journal_entry_obj?.group}
{obj_hide}
{obj_enable} -->

    <!-- Set/unset priority (boolean) -->
    <button
        type="button"
        onclick={() => {
            obj_priority = !obj_priority;
            // update_journal_entry();
        }}
        class="btn-icon btn-icon-sm md:btn-icon-base preset-tonal-tertiary hover:preset-filled-tertiary-500 transition"
        title="Toggle priority of this journal entry">
        {#if obj_priority}
            <Flag strokeWidth="2.5" color="green" class="inline-block" />
        {:else}
            <FlagOff strokeWidth="1" color="gray" class="inline-block" />
        {/if}
        <span class="hidden lg:inline"> Priority </span>
    </button>

    <!-- Set sort order (number) -->
    <span
        class:hidden={!$ae_loc.edit_mode}
        class="flex flex-row flex-wrap items-center justify-center rounded-lg border border-gray-300">
        <button
            type="button"
            onclick={() => {
                obj_sort = obj_sort ? obj_sort + 1 : 1;
                // update_journal_entry();
            }}
            class="btn-icon btn-icon-sm preset-tonal-tertiary hover:preset-filled-tertiary-500 transition"
            title="Increment sort order of this journal entry">
            <Plus strokeWidth="2.5" color="blue" />
        </button>
        <span class="mx-1">
            {#if obj_sort}
                {obj_sort}
            {:else}
                <!-- <ArrowDown01 /> -->
                <ArrowDown10 />
            {/if}
        </span>
        <button
            type="button"
            onclick={() => {
                obj_sort = obj_sort ? obj_sort - 1 : 0;
                // update_journal_entry();
            }}
            class="btn-icon btn-icon-sm preset-tonal-tertiary hover:preset-filled-tertiary-500 transition"
            title="Decrement sort order of this journal entry">
            <Minus strokeWidth="2.5" color="blue" />
        </button>
    </span>

    <!-- Set group (string) -->
    <input
        type="text"
        bind:value={obj_group}
        placeholder="Group"
        onchange={() => {
            // update_journal_entry();
        }}
        class:hidden={!$ae_loc.edit_mode}
        class="input input-sm input-bordered w-24"
        title="Set group (for sorting) of this journal entry" />

    <!-- Set archive datetime (string) -->
    <span
        class="flex flex-row flex-wrap items-center justify-center rounded-lg border border-gray-200">
        <input
            type="datetime-local"
            bind:value={obj_archive_on}
            placeholder="Archive On"
            onchange={() => {
                // update_journal_entry();
            }}
            class:hidden={!$ae_loc.edit_mode}
            class="input input-sm input-bordered w-auto border-none"
            title="Set archive on datetime for archiving this journal entry" />

        {#if obj_archive_on}
            <!-- Button to clear the datetime -->
            <button
                type="button"
                onclick={() => {
                    obj_archive_on = null;
                    // update_journal_entry();
                }}
                class:hidden={!$ae_loc.edit_mode}
                class="btn-icon btn-icon-sm preset-tonal-warning hover:preset-filled-warning-500 transition"
                title="Clear the archive on datetime for this journal entry">
                <X strokeWidth="2.5" color="red" />
                <!-- <span class="hidden">Clear Archive</span> -->
            </button>
        {:else}
            <!-- Button to set the datetime to now -->
            <button
                type="button"
                onclick={() => {
                    // tmp_entry_obj.archive_on = new Date().toISOString();
                    // console.log('Archive on datetime set to now:', tmp_entry_obj.archive_on);
                    obj_archive_on = new Date().toISOString();
                    console.log(
                        'Archive on datetime set to now:',
                        tmp_entry_obj.archive_on
                    );
                    // update_journal_entry();
                }}
                class:hidden={!$ae_loc.edit_mode}
                class="btn-icon btn-icon-sm preset-tonal-warning hover:preset-filled-warning-500 transition"
                title="Set the archive on datetime for this journal entry">
                <Clock strokeWidth="2.5" color="blue" />
                <!-- <span class="hidden">Set Archive</span> -->
            </button>
        {/if}
    </span>

    <!-- Set/unset hide (boolean) -->
    <button
        type="button"
        onclick={() => {
            obj_hide = !obj_hide;
            update_journal_entry();
        }}
        class="btn btn-sm md:btn-md preset-tonal-warning hover:preset-filled-warning-500 transition"
        title="Toggle visibility of this journal entry">
        {#if obj_hide}
            <EyeOff strokeWidth="1" color="red" class="inline-block" />
            <span class="hidden md:inline">Hidden</span>
        {:else}
            <Eye strokeWidth="2.5" color="green" class="inline-block" />
            <span class="hidden md:inline">Visible</span>
        {/if}
    </button>

    <!-- Set/unset enable (boolean) -->
    <button
        type="button"
        onclick={() => {
            obj_enable = !obj_enable;
            // update_journal_entry();
        }}
        class:hidden={!$ae_loc.administrator_access || !$ae_loc.edit_mode}
        class="btn btn-sm md:btn-md preset-tonal-error hover:preset-filled-error-500 transition"
        title="Toggle enable status of this journal entry">
        {#if obj_enable}
            <ShieldCheck strokeWidth="2.5" color="green" class="inline-block" />
            <span class="hidden md:inline">Enabled</span>
        {:else}
            <ShieldMinus strokeWidth="1" color="red" class="inline-block" />
            <span class="hidden md:inline">Disabled</span>
        {/if}
    </button>

    <!-- Delete journal entry -->
    <button
        type="button"
        onclick={() => {
            if (
                confirm(`Are you sure you want to delete this journal entry?`)
            ) {
                let delete_method = 'disable';
                if ($ae_loc.administrator_access && $ae_loc.edit_mode) {
                    delete_method = 'delete';
                }
                journals_func
                    .delete_ae_obj_id__journal_entry({
                        api_cfg: $ae_api,
                        journal_entry_id:
                            lq__journal_entry_obj?.journal_entry_id,
                        method: delete_method as 'delete' | 'disable' | 'hide',
                        log_lvl: log_lvl
                    })
                    .then(() => {
                        // Optionally, you can provide feedback to the user
                        alert('Journal entry deleted successfully!');
                    })
                    .catch((error: any) => {
                        console.error('Error deleting journal entry:', error);
                        alert('Failed to delete journal entry.');
                    })
                    .finally(() => {
                        $journals_slct.journal_id = null;
                        $journals_slct.journal_obj = null;
                        goto(`/journals/${lq__journal_entry_obj?.journal_id}`);
                    });
            }
        }}
        class:hidden={!$ae_loc.edit_mode}
        class="btn btn-sm md:btn-md preset-tonal-error hover:preset-filled-error-500 transition"
        title="Delete this journal entry">
        {#if $ae_loc.administrator_access && $ae_loc.edit_mode}
            <FileX strokeWidth="2.5" color="red" class="inline-block" />
            <span class="hidden md:inline">Delete</span>
        {:else}
            <Trash2 strokeWidth="2.5" color="orange" class="inline-block" />
            <span class="hidden md:inline">Remove</span>
        {/if}
    </button>

    <span
        class="flex flex-row items-center justify-center text-sm text-gray-500">
        {#if !$ae_loc.edit_mode}
            <span class="">
                {ae_util.iso_datetime_formatter(
                    lq__journal_entry_obj?.created_on,
                    'datetime_iso_12_no_seconds'
                )}
                {lq__journal_entry_obj?.updated_on
                    ? ` | Last updated: ${ae_util.iso_datetime_formatter(lq__journal_entry_obj?.updated_on, 'datetime_iso_12_no_seconds')}`
                    : ''}
            </span>
        {:else}
            <span class="">
                {ae_util.iso_datetime_formatter(
                    lq__journal_entry_obj?.created_on,
                    'datetime_iso_tz'
                )}
                {lq__journal_entry_obj?.updated_on
                    ? ` | Last updated: ${ae_util.iso_datetime_formatter(lq__journal_entry_obj?.updated_on, 'datetime_iso_tz')}`
                    : ''}
            </span>
        {/if}
    </span>

    <!-- Select option list of Journals to choose from. This is used to assign the Journal Entry to a different Journal ID. -->
    {#if $ae_loc.edit_mode && lq__journal_obj_li?.length}
        <div
            class="flex flex-row flex-wrap items-center justify-start gap-2 rounded-lg border border-gray-200">
            <SquareLibrary size="1em" class="mx-1" />
            <span class="hidden text-sm text-gray-500 sm:inline">
                Journal:
            </span>
            <select
                class="novi_btn btn btn-secondary btn-sm
        preset-tonal-primary
        hover:preset-filled-primary-500
        border-none
        text-xs
        transition
        "
                bind:value={tmp_entry_obj.journal_id}
                onchange={(event) => {
                    tmp_entry_obj.journal_id = (
                        event.target as HTMLInputElement
                    ).value;
                    console.log('Selected journal:', tmp_entry_obj.journal_id);
                    if (
                        confirm(
                            `Are you sure you want to change the journal for this entry?`
                        )
                    ) {
                        change_journal_id();
                    }
                }}
                title="Select a different journal for this entry">
                <option value="">Select Journal</option>
                {#each lq__journal_obj_li as journal (journal.journal_id)}
                    <option
                        value={journal.journal_id}
                        title={`Journal: ${journal.name}`}>
                        {journal.name}
                    </option>
                {/each}
            </select>
        </div>
    {/if}
</section>
