<script lang="ts">
/**
 * ae_comp__modal_journal_entry_config.svelte
 * Standardized Journal Entry-level configuration.
 */
import {
    ArrowDownToLine,
    ArrowUpToLine,
    Check,
    CodeXml,
    Copy,
    FileDown,
    FingerprintPattern,
    Minus,
    RefreshCcw,
    Settings,
    Shapes,
    ShieldCheck,
    Tag,
    Trash2,
    X,
    Zap
} from '@lucide/svelte';
import { goto } from '$app/navigation';
import { Modal } from 'flowbite-svelte';
import { ae_loc, ae_api } from '$lib/stores/ae_stores';
import { journals_func } from '$lib/ae_journals/ae_journals_functions';
import AE_Comp_Editor_CodeMirror from '$lib/elements/element_editor_codemirror.svelte';
import AE_Object_Flags from '$lib/ae_elements/AE_Object_Flags.svelte';
import type { ae_Journal, ae_JournalEntryDraft } from '$lib/types/ae_types';

interface Props {
    log_lvl?: number;
    show?: boolean;
    journal: ae_Journal;
    tmp_entry_obj: ae_JournalEntryDraft; // Bindable
    on_save: () => void;
    on_force_reset?: () => void;
    on_show_export?: () => void;
    on_append?: () => void;
    on_prepend?: () => void;
}

let {
    log_lvl = $bindable(0),
    show = $bindable(false),
    journal,
    tmp_entry_obj = $bindable(),
    on_save,
    on_force_reset,
    on_show_export,
    on_append,
    on_prepend
}: Props = $props();

let tab: 'actions' | 'meta' | 'security' | 'json' = $state('actions');

const normalize_date = (val?: string | Date | null) => {
    if (!val) return null;
    if (val instanceof Date) return val.toISOString().slice(0, 16);
    return val.slice(0, 16);
};

const panel_class =
    'space-y-4 rounded-xl border border-surface-500/20 bg-surface-500/5 p-4 shadow-sm';
const panel_title_class =
    'flex items-center gap-2 border-b border-surface-500/20 pb-2 text-lg font-bold';
const field_card_class =
    'bg-surface-500/5 border-surface-500/10 flex cursor-pointer items-center space-x-3 rounded-lg border p-3 transition-colors hover:bg-surface-500/10';
const tab_button_base_class = 'btn btn-sm border transition-all duration-200';
const tab_button_active_class =
    'border-surface-200-800 bg-surface-200-800 text-surface-950-50 shadow-sm';
const tab_button_inactive_class =
    'border-transparent bg-surface-50-900/60 text-surface-600-400 hover:border-surface-200-800 hover:bg-surface-100-900 hover:text-surface-950-50';

function tab_button_class(is_active: boolean): string {
    return `${tab_button_base_class} ${is_active ? tab_button_active_class : tab_button_inactive_class}`;
}

async function handle_update_entry() {
    try {
        // WHITELISTED BASE TABLE COLUMNS ONLY
        const journal_entry_id = tmp_entry_obj.journal_entry_id;
        if (!journal_entry_id) {
            console.error('Journal entry ID missing for update.');
            return;
        }

        const data_kv = {
            name: tmp_entry_obj.name,
            short_name: tmp_entry_obj.short_name,
            summary: tmp_entry_obj.summary,
            content: tmp_entry_obj.content,
            category_code: tmp_entry_obj.category_code,
            type_code: tmp_entry_obj.type_code,
            topic_code: tmp_entry_obj.topic_code,
            tags: tmp_entry_obj.tags,
            passcode_hash: tmp_entry_obj.passcode_hash,
            private: tmp_entry_obj.private,
            public: tmp_entry_obj.public,
            personal: tmp_entry_obj.personal,
            professional: tmp_entry_obj.professional,
            alert: tmp_entry_obj.alert,
            alert_msg: tmp_entry_obj.alert_msg,
            enable: tmp_entry_obj.enable,
            hide: tmp_entry_obj.hide,
            priority: tmp_entry_obj.priority,
            sort: tmp_entry_obj.sort,
            group: tmp_entry_obj.group,
            notes: tmp_entry_obj.notes,
            archive_on: tmp_entry_obj.archive_on,
            template: tmp_entry_obj.template,
            data_json: tmp_entry_obj.data_json
        };

        await journals_func.update_ae_obj__journal_entry({
            api_cfg: $ae_api,
            journal_entry_id,
            data_kv: data_kv,
            log_lvl: log_lvl
        });
    } catch (error) {
        console.error('Error updating journal entry:', error);
    }
}

async function handle_admin_delete_action() {
    const can_delete = $ae_loc.manager_access || $ae_loc.administrator_access;
    const delete_method = can_delete ? 'delete' : 'disable';
    const action_label = can_delete ? 'delete' : 'remove';
    const confirm_label = can_delete ? 'delete' : 'remove';
    const journal_entry_id = tmp_entry_obj.journal_entry_id;

    if (!journal_entry_id) {
        console.error('Journal entry ID missing for delete action.');
        return;
    }

    if (
        !confirm(
            `Are you sure you want to ${confirm_label} this journal entry?`
        )
    ) {
        return;
    }

    try {
        await journals_func.delete_ae_obj_id__journal_entry({
            api_cfg: $ae_api,
            journal_entry_id,
            method: delete_method,
            log_lvl
        });

        show = false;
        await goto(`/journals/${tmp_entry_obj.journal_id}`);
    } catch (error) {
        console.error(
            `Error attempting to ${action_label} journal entry:`,
            error
        );
        alert(`Failed to ${action_label} journal entry.`);
    }
}
</script>

<Modal
    bind:open={show}
    autoclose={false}
    dismissable={false}
    placement="top-center"
    size="lg"
    class="border-surface-200-800 bg-surface-50-900 text-surface-950-50 relative mx-auto flex h-[calc(100dvh-2rem)] max-h-[calc(100dvh-2rem)] w-full flex-col rounded-xl border shadow-xl"
    headerClass="flex w-full flex-row items-center justify-between gap-2 rounded-t-xl border-b border-surface-200-800 bg-surface-100-900 p-4"
    footerClass="mt-auto flex w-full shrink-0 flex-row items-center justify-center gap-2 rounded-b-xl border-t border-surface-200-800 bg-surface-100-900 p-4">
    {#snippet header()}
        <h3 class="flex flex-1 items-center gap-2 text-lg font-bold">
            <Settings class="text-primary-500" />
            <span>Entry Config: {tmp_entry_obj.name || '--'}</span>
        </h3>
        <button
            type="button"
            class="btn-icon btn-icon-sm preset-tonal-surface ml-2"
            onclick={() => (show = false)}>
            <X size="1.1em" />
        </button>
    {/snippet}

    <div class="min-h-0 flex-1 space-y-6 overflow-y-auto px-4 py-3">
        <!-- Navigation Tabs -->
        <div
            class="bg-surface-500/10 sticky top-0 z-10 mx-auto mb-4 flex max-w-fit justify-center gap-1 rounded-lg p-1 backdrop-blur-sm">
            <button
                type="button"
                class={tab_button_class(tab === 'actions')}
                onclick={() => (tab = 'actions')}>
                <Zap size="1.1em" class="mr-1" /> Quick Actions
            </button>
            <button
                type="button"
                class={tab_button_class(tab === 'meta')}
                onclick={() => (tab = 'meta')}>
                <Shapes size="1.1em" class="mr-1" /> Metadata
            </button>
            <button
                type="button"
                class={tab_button_class(tab === 'security')}
                onclick={() => (tab = 'security')}>
                <ShieldCheck size="1.1em" class="mr-1" /> Status & Security
            </button>
            <button
                type="button"
                class={tab_button_class(tab === 'json')}
                onclick={() => (tab = 'json')}>
                <CodeXml size="1.1em" class="mr-1" /> JSON
            </button>
        </div>

        {#if tab === 'actions'}
            <div class="animate-in fade-in space-y-4 duration-300">
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Zap size="1.2em" class="text-primary-500" />
                        Quick Actions
                    </h2>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <button
                            type="button"
                            class="btn preset-tonal-secondary w-full justify-start gap-2"
                            onclick={() => {
                                show = false;
                                on_prepend?.();
                            }}>
                            <ArrowUpToLine size="1.2em" />
                            Prepend Content
                        </button>
                        <button
                            type="button"
                            class="btn preset-tonal-secondary w-full justify-start gap-2"
                            onclick={() => {
                                show = false;
                                on_append?.();
                            }}>
                            <ArrowDownToLine size="1.2em" />
                            Append Content
                        </button>
                        <button
                            type="button"
                            class="btn preset-tonal-surface w-full justify-start gap-2"
                            onclick={() => {
                                show = false;
                                on_show_export?.();
                            }}>
                            <FileDown size="1.2em" />
                            Export Entry
                        </button>
                        <button
                            type="button"
                            class="btn preset-tonal-surface w-full justify-start gap-2"
                            onclick={() => {
                                /* Clone logic here */ alert(
                                    'Clone not yet implemented in modal'
                                );
                            }}>
                            <Copy size="1.2em" />
                            Clone Entry
                        </button>
                    </div>
                </section>

                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Shapes size="1.2em" class="text-primary-500" />
                        Quick Category
                    </h2>
                    <div class="flex flex-wrap gap-2">
                        {#each journal?.cfg_json?.category_li ?? [] as cat (cat.code)}
                            <button
                                type="button"
                                class="btn btn-sm {tmp_entry_obj.category_code ===
                                cat.code
                                    ? 'preset-filled-primary'
                                    : 'preset-tonal-primary'}"
                                onclick={() => {
                                    tmp_entry_obj.category_code = cat.code;
                                    handle_update_entry();
                                    on_save();
                                }}>
                                {cat.name}
                            </button>
                        {/each}
                    </div>
                </section>
            </div>
        {:else if tab === 'meta'}
            <div class="animate-in fade-in space-y-4 duration-300">
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <Shapes size="1.2em" class="text-primary-500" />
                        Entry Details
                    </h2>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        <label class="label">
                            <span class="text-sm font-bold opacity-70"
                                >Category</span>
                            <select
                                class="select"
                                bind:value={tmp_entry_obj.category_code}
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }}>
                                <option value="">None</option>
                                {#each journal?.cfg_json?.category_li ?? [] as cat (cat.code)}
                                    <option value={cat.code}>{cat.name}</option>
                                {/each}
                            </select>
                        </label>

                        <label class="label">
                            <span class="text-sm font-bold opacity-70"
                                >Tags (Comma separated)</span>
                            <div class="flex items-center gap-2">
                                <Tag size="1.2em" class="opacity-30" />
                                <input
                                    type="text"
                                    bind:value={tmp_entry_obj.tags}
                                    class="input grow"
                                    placeholder="meeting, urgent, ideas"
                                    onchange={() => {
                                        handle_update_entry();
                                        on_save();
                                    }} />
                            </div>
                        </label>

                        <label class="label md:col-span-2">
                            <span class="text-sm font-bold opacity-70"
                                >Summary</span>
                            <textarea
                                bind:value={tmp_entry_obj.summary}
                                class="textarea min-h-24"
                                placeholder="Short summary for search results and quick review"
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }}></textarea>
                        </label>

                        <label class="label md:col-span-2">
                            <span class="text-sm font-bold opacity-70"
                                >Archive On</span>
                            <input
                                type="datetime-local"
                                value={normalize_date(tmp_entry_obj.archive_on)}
                                onchange={(e) => {
                                    tmp_entry_obj.archive_on =
                                        e.currentTarget.value;
                                    handle_update_entry();
                                    on_save();
                                }}
                                class="input" />
                        </label>

                        {#if !journal?.cfg_json?.hide_btn_template}
                            <label class={field_card_class}>
                                <input
                                    type="checkbox"
                                    bind:checked={tmp_entry_obj.template}
                                    onchange={() => {
                                        handle_update_entry();
                                        on_save();
                                    }}
                                    class="checkbox checkbox-primary" />
                                <div class="flex flex-col">
                                    <span class="font-bold">Template</span>
                                    <span class="text-xs opacity-60">
                                        Mark this entry as a reusable template
                                    </span>
                                </div>
                            </label>
                        {/if}
                    </div>
                </section>
            </div>
        {:else if tab === 'security'}
            <div class="animate-in fade-in space-y-4 duration-300">
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <ShieldCheck size="1.2em" class="text-primary-500" />
                        Status
                    </h2>
                    <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                        {#if tmp_entry_obj.alert}
                            <label
                                class="label flex flex-col items-start gap-1 md:col-span-2">
                                <span class="text-sm font-bold opacity-70"
                                    >Alert Message</span>
                                <textarea
                                    bind:value={tmp_entry_obj.alert_msg}
                                    class="textarea min-h-24 w-full"
                                    placeholder="Optional alert or notice shown with the entry"
                                    onchange={() => {
                                        handle_update_entry();
                                        on_save();
                                    }}></textarea>
                                <span class="text-xs opacity-60">
                                    Shown when Alert is enabled.
                                </span>
                            </label>
                        {/if}

                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_entry_obj.alert}
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }}
                                class="checkbox checkbox-primary" />
                            <div class="flex flex-col">
                                <span class="font-bold">Alert</span>
                                <span class="text-xs opacity-60">
                                    Action required or reminder.
                                </span>
                            </div>
                        </label>

                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_entry_obj.priority}
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }}
                                class="checkbox checkbox-primary" />
                            <div class="flex flex-col">
                                <span class="font-bold">Priority Entry</span>
                                <span class="text-xs opacity-60">
                                    Pin this entry ahead of the standard order.
                                </span>
                            </div>
                        </label>

                        <label
                            class="bg-surface-500/5 border-surface-500/10 flex items-center justify-between rounded-lg border p-3">
                            <div class="flex flex-col">
                                <span class="text-sm font-bold"
                                    >Sort Order</span>
                                <span class="text-xs opacity-60">
                                    Lower numbers appear earlier in lists.
                                </span>
                            </div>
                            <input
                                type="number"
                                bind:value={tmp_entry_obj.sort}
                                class="input input-sm w-24 text-right" />
                        </label>

                        <label class={field_card_class}>
                            <input
                                type="checkbox"
                                bind:checked={tmp_entry_obj.hide}
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }}
                                class="checkbox checkbox-primary" />
                            <div class="flex flex-col">
                                <span class="font-bold">Hidden</span>
                                <span class="text-xs opacity-60">
                                    Hide from standard lists.
                                </span>
                            </div>
                        </label>
                    </div>
                </section>

                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <FingerprintPattern
                            size="1.2em"
                            class="text-primary-500" />
                        Security and Privacy
                    </h2>
                    <div
                        class="border-surface-500/10 bg-surface-500/5 space-y-4 rounded-xl border p-4">
                        <label class="label flex flex-col items-start gap-1">
                            <span class="text-sm font-bold opacity-70"
                                >Passcode</span>
                            <input
                                type="password"
                                bind:value={tmp_entry_obj.passcode_hash}
                                class="input w-full"
                                placeholder="journal_entry.passcode_hash"
                                onchange={() => {
                                    handle_update_entry();
                                    on_save();
                                }} />
                            <span class="text-xs opacity-60">
                                Stored on the entry as passcode_hash.
                            </span>
                        </label>

                        <div class="space-y-2">
                            <p
                                class="text-xs font-semibold tracking-wider uppercase opacity-60">
                                Visibility and audience
                            </p>
                            <AE_Object_Flags
                                bind:obj={tmp_entry_obj}
                                show_labels={false}
                                on_toggle={() => {
                                    handle_update_entry();
                                    on_save();
                                }}
                                hide_alert={true}
                                hide_private={journal?.cfg_json
                                    ?.hide_btn_private}
                                hide_public={journal?.cfg_json?.hide_btn_public}
                                hide_personal={journal?.cfg_json
                                    ?.hide_btn_personal}
                                hide_professional={journal?.cfg_json
                                    ?.hide_btn_professional}
                                hide_template={true} />
                        </div>
                    </div>
                </section>

                {#if tmp_entry_obj.private && !tmp_entry_obj.content && tmp_entry_obj.content_encrypted}
                    <section class={panel_class}>
                        <h2 class={panel_title_class}>
                            <RefreshCcw size="1.2em" class="text-primary-500" />
                            Disaster Recovery
                        </h2>
                        <div class="space-y-4">
                            <p class="text-xs italic opacity-70">
                                If the encryption passcode is lost, the data is
                                unrecoverable. You can force a reset to plain
                                text to reuse this entry ID.
                            </p>
                            <button
                                type="button"
                                class="btn btn-sm preset-tonal-error hover:preset-filled-error-500 w-full font-bold"
                                onclick={() => {
                                    show = false;
                                    on_force_reset?.();
                                }}>
                                Force Reset to Plain Text
                            </button>
                        </div>
                    </section>
                {/if}

                <details
                    class="border-surface-500/20 bg-surface-500/5 rounded-xl border shadow-sm">
                    <summary
                        class="border-surface-500/20 flex cursor-pointer items-center gap-2 border-b px-4 py-3 text-lg font-bold">
                        <Settings size="1.2em" class="text-primary-500" />
                        Admin
                    </summary>
                    <div class="space-y-4 p-4">
                        <p class="text-xs opacity-60">
                            Trusted access and above only. Notes are for staff
                            use; managers and admins see Delete while trusted
                            access sees Remove.
                        </p>

                        <div class="grid grid-cols-1 gap-4">
                            <label class="label">
                                <span class="text-sm font-bold opacity-70"
                                    >Notes</span>
                                <textarea
                                    bind:value={tmp_entry_obj.notes}
                                    class="textarea min-h-24"
                                    placeholder="Rarely used special case admin/staff notes"
                                    onchange={() => {
                                        handle_update_entry();
                                        on_save();
                                    }}></textarea>
                            </label>

                            <div class="grid grid-cols-1 gap-4 md:grid-cols-2">
                                <label class={field_card_class}>
                                    <input
                                        type="checkbox"
                                        bind:checked={tmp_entry_obj.enable}
                                        onchange={() => {
                                            handle_update_entry();
                                            on_save();
                                        }}
                                        class="checkbox checkbox-primary" />
                                    <div class="flex flex-col">
                                        <span class="font-bold">Enabled</span>
                                        <span class="text-xs opacity-60">
                                            Allow default access for AE object
                                            type; essentially marked for
                                            deletion.
                                        </span>
                                    </div>
                                </label>

                                <button
                                    type="button"
                                    class="btn btn-sm mx-auto inline-flex w-fit min-w-36 justify-center gap-2 px-4 font-bold {$ae_loc.manager_access ||
                                    $ae_loc.administrator_access
                                        ? 'preset-tonal-error hover:preset-filled-error-500'
                                        : 'preset-tonal-warning hover:preset-filled-warning-500'}"
                                    title={$ae_loc.manager_access ||
                                    $ae_loc.administrator_access
                                        ? 'Permanently delete this journal entry'
                                        : 'Disable this journal entry instead of deleting it'}
                                    onclick={handle_admin_delete_action}>
                                    {#if $ae_loc.manager_access || $ae_loc.administrator_access}
                                        <Trash2 size="1.1em" />
                                        Delete
                                    {:else}
                                        <Minus size="1.1em" />
                                        Remove
                                    {/if}
                                </button>
                            </div>
                        </div>
                    </div>
                </details>
            </div>
        {:else if tab === 'json'}
            <div class="h-full min-h-100">
                <section class={panel_class}>
                    <h2 class={panel_title_class}>
                        <CodeXml size="1.2em" class="text-primary-500" />
                        Raw Entry JSON
                    </h2>
                    <p class="text-xs opacity-60">
                        Read-only view of the current bound entry object.
                    </p>
                    <AE_Comp_Editor_CodeMirror
                        readonly={true}
                        content={JSON.stringify(tmp_entry_obj, null, 2)}
                        theme_mode={$ae_loc.theme_mode}
                        class_li="rounded-lg border border-surface-500/20" />
                </section>
            </div>
        {/if}
    </div>

    {#snippet footer()}
        <button
            type="button"
            class="btn preset-filled-primary min-w-30 font-bold"
            onclick={() => (show = false)}>
            <Check size="1.2em" class="mr-2" />
            Done
        </button>
    {/snippet}
</Modal>
