<script lang="ts">
import { Modal } from 'flowbite-svelte';
import { Check, X } from '@lucide/svelte';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';
import { ae_api } from '$lib/stores/ae_stores';
import type { key_val } from '$lib/stores/ae_stores';
import type { ae_JournalEntryDraft } from '$lib/types/ae_types';

interface Props {
    open: boolean;
    journal_entry: ae_JournalEntryDraft;
    journal_config: key_val; // The cfg_json from the journal object
    mode?: 'append' | 'prepend' | 'auto';
    on_close: () => void;
    on_update: () => void;
    log_lvl?: number;
}

let {
    open = $bindable(false),
    journal_entry,
    journal_config,
    mode = 'auto',
    on_close,
    on_update,
    log_lvl = 0
}: Props = $props();
// Local State
let tmp_entry_obj: ae_JournalEntryDraft = $state({});

// Header Options
let add_timestamp_header: boolean = $state(true);
let add_timestamp_header_w_day_of_week: boolean = $state(true);
let add_text_header: string = $state('');
let add_text: string = $state('');

// Change detection
let has_changes: boolean = $derived(
    add_text_header.length > 0 || add_text.length > 0
);

// Initialize tmp object when entry changes or modal opens
$effect(() => {
    if (open && journal_entry) {
        tmp_entry_obj = JSON.parse(JSON.stringify(journal_entry));
        // Reset fields
        add_text_header = '';
        add_text = '';
    }
});

async function handle_save() {
    let current_entry_content =
        typeof tmp_entry_obj?.content === 'string' ? tmp_entry_obj.content : '';
    let add_content = '';
    let new_content = current_entry_content;

    // Construct the header/content to add (Following original logic)
    let timestamp_str = ae_util.iso_datetime_formatter(
        new Date(),
        'datetime_iso_12_no_seconds'
    );
    let day_of_week_str = add_timestamp_header_w_day_of_week
        ? ' (' + ae_util.iso_datetime_formatter(new Date(), 'week_long') + ')'
        : '';

    if (add_timestamp_header && add_text_header) {
        add_content =
            '## ' +
            timestamp_str +
            day_of_week_str +
            ' - ' +
            add_text_header.trim() +
            '\n' +
            add_text.trim() +
            '\n\n';
    } else if (add_timestamp_header) {
        add_content =
            '## ' +
            timestamp_str +
            day_of_week_str +
            '\n' +
            add_text.trim() +
            '\n\n';
    } else if (add_text_header) {
        add_content =
            '## ' +
            add_text_header.trim() +
            day_of_week_str +
            '\n' +
            add_text.trim() +
            '\n\n';
    } else {
        add_content = add_text.trim() + '\n\n';
    }

    // Determine Append or Prepend
    let effective_mode = mode;
    if (effective_mode === 'auto') {
        effective_mode = journal_config?.entry_add_text || 'append';
    }

    if (effective_mode == 'prepend') {
        new_content = add_content + new_content;
    } else {
        // Append
        new_content = new_content.trim() + '\n\n' + add_content;
    }

    new_content = new_content.trim() + '\n';

    let data_kv = { content: new_content };
    const journal_entry_id = tmp_entry_obj.journal_entry_id;
    if (!journal_entry_id) {
        console.error('Journal entry ID missing for append save.');
        return;
    }

    try {
        let update_result = await journals_func.update_ae_obj__journal_entry({
            api_cfg: $ae_api,
            journal_entry_id,
            data_kv: data_kv,
            log_lvl: log_lvl
        });

        if (update_result) {
            // Success
            on_update();
            open = false;
        } else {
            alert('Failed to update journal entry.');
        }
    } catch (error) {
        console.error('Error updating journal entry:', error);
        alert('Failed to update journal entry.');
    }
}
</script>

<Modal
    title="{(mode === 'auto' ? journal_config?.entry_add_text : mode) ==
    'append'
        ? 'Append to'
        : 'Prepend to'} Journal Entry: {journal_entry?.name ??
        journal_entry?.created_on}"
    bind:open
    autoclose={false}
    placement="top-center"
    size="xl"
    class="top-center relative mx-auto flex w-full flex-col gap-1 divide-gray-200 rounded-lg border-gray-200 bg-white text-gray-800 shadow-md dark:divide-gray-700 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200">
    <div class="flex flex-col gap-3">
        <!-- Checkbox Options -->
        <div class="flex flex-wrap gap-4">
            <label class="flex items-center gap-2">
                <input
                    type="checkbox"
                    id="append_timestamp_header"
                    bind:checked={add_timestamp_header}
                    class="checkbox" />
                <span>Use timestamp as Markdown header</span>
            </label>

            <label class="flex items-center gap-2">
                <input
                    type="checkbox"
                    id="append_timestamp_header_w_day_of_week"
                    bind:checked={add_timestamp_header_w_day_of_week}
                    class="checkbox" />
                <span>Include day of week</span>
            </label>
        </div>

        <!-- Text Header Input -->
        <input
            type="text"
            placeholder="Markdown header for content (Optional)"
            bind:value={add_text_header}
            class="input" />

        <!-- Main Content Area -->
        <textarea
            bind:value={add_text}
            class="textarea min-h-48"
            placeholder="Content to {mode === 'auto'
                ? journal_config?.entry_add_text
                : mode}...">
        </textarea>

        <div class="mt-2 flex justify-end gap-2">
            <button
                type="button"
                disabled={!has_changes}
                onclick={handle_save}
                class="btn preset-filled-primary"
                class:opacity-50={!has_changes}>
                <Check class="mr-1" />
                Update
            </button>
            <button
                type="button"
                onclick={on_close}
                class="btn preset-tonal-surface">
                <X class="mr-1" />
                Cancel
            </button>
        </div>
    </div>
</Modal>
