<script lang="ts">
    /**
     * ae_comp__modal_journal_entry_config.svelte
     * Standardized Journal Entry-level configuration.
     */
    import {
        Check,
        Settings,
        X,
        Database,
        CodeXml,
        ShieldCheck,
        Fingerprint,
        Trash2,
        Clock,
        Shapes,
        ArrowUpToLine,
        ArrowDownToLine,
        FileDown,
        Copy,
        RefreshCcw,
        Tag,
        Plus,
        Minus,
        Zap
    } from 'lucide-svelte';
    import { Modal } from 'flowbite-svelte';
    import { ae_loc, ae_api } from '$lib/stores/ae_stores';
    import {
        journals_loc,
        journals_sess
    } from '$lib/ae_journals/ae_journals_stores';
    import { journals_func } from '$lib/ae_journals/ae_journals_functions';
    import AE_Comp_Editor_CodeMirror from '$lib/elements/AE_Comp_Editor_CodeMirror.svelte';
    import AE_Object_Flags from '$lib/ae_elements/AE_Object_Flags.svelte';

    interface Props {
        log_lvl?: number;
        show?: boolean;
        entry: any;
        journal: any;
        tmp_entry_obj: any; // 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),
        entry,
        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 | null) =>
        val ? val.slice(0, 16) : null;

    async function handle_update_entry() {
        try {
            // WHITELISTED BASE TABLE COLUMNS ONLY
            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,
                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: tmp_entry_obj.journal_entry_id,
                data_kv: data_kv,
                log_lvl: log_lvl
            });
        } catch (error) {
            console.error('Error updating journal entry:', error);
        }
    }
</script>

<Modal
    bind:open={show}
    autoclose={false}
    dismissable={false}
    placement="top-center"
    size="lg"
    class="relative flex flex-col mx-auto w-full bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 border border-orange-300 dark:border-orange-700 rounded-lg shadow-xl"
    headerClass="flex flex-row gap-2 items-center justify-between w-full bg-orange-100 dark:bg-orange-900 p-4 rounded-t-lg border-b border-orange-200 dark:border-orange-800"
    footerClass="flex flex-row gap-2 items-center justify-center w-full bg-orange-100 dark:bg-orange-900 p-4 rounded-b-lg border-t border-orange-200 dark:border-orange-800"
>
    {#snippet header()}
        <h3 class="flex-1 flex 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="space-y-6 py-2 h-[60vh] overflow-y-auto px-4">
        <!-- Navigation Tabs -->
        <div
            class="flex justify-center gap-1 mb-4 p-1 bg-surface-500/10 rounded-lg max-w-fit mx-auto sticky top-0 z-10 backdrop-blur-sm"
        >
            <button
                type="button"
                class="btn btn-sm transition-all {tab === 'actions'
                    ? 'preset-filled-primary'
                    : 'preset-tonal-surface'}"
                onclick={() => (tab = 'actions')}
            >
                <Zap size="1.1em" class="mr-1" /> Quick Actions
            </button>
            <button
                type="button"
                class="btn btn-sm transition-all {tab === 'meta'
                    ? 'preset-filled-primary'
                    : 'preset-tonal-surface'}"
                onclick={() => (tab = 'meta')}
            >
                <Shapes size="1.1em" class="mr-1" /> Metadata
            </button>
            <button
                type="button"
                class="btn btn-sm transition-all {tab === 'security'
                    ? 'preset-filled-primary'
                    : 'preset-tonal-surface'}"
                onclick={() => (tab = 'security')}
            >
                <ShieldCheck size="1.1em" class="mr-1" /> Status & Security
            </button>
            <button
                type="button"
                class="btn btn-sm transition-all {tab === 'json'
                    ? 'preset-filled-primary'
                    : 'preset-tonal-surface'}"
                onclick={() => (tab = 'json')}
            >
                <CodeXml size="1.1em" class="mr-1" /> JSON
            </button>
        </div>

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

                <section class="space-y-4 pt-4 border-t border-surface-500/20">
                    <h4 class="text-xs font-bold uppercase opacity-50">
                        Quick Category
                    </h4>
                    <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="space-y-6 animate-in fade-in duration-300">
                <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 gap-2 items-center">
                        <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>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <label class="label">
                        <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>
                    <label class="label">
                        <span class="text-sm font-bold opacity-70"
                            >Sort Priority</span
                        >
                        <div class="flex items-center gap-2">
                            <button
                                type="button"
                                class="btn-icon btn-icon-sm preset-tonal-surface"
                                onclick={() => {
                                    tmp_entry_obj.sort =
                                        (tmp_entry_obj.sort ?? 0) - 1;
                                    handle_update_entry();
                                    on_save();
                                }}><Minus size="1em" /></button
                            >
                            <span class="font-mono font-bold w-8 text-center"
                                >{tmp_entry_obj.sort ?? 0}</span
                            >
                            <button
                                type="button"
                                class="btn-icon btn-icon-sm preset-tonal-surface"
                                onclick={() => {
                                    tmp_entry_obj.sort =
                                        (tmp_entry_obj.sort ?? 0) + 1;
                                    handle_update_entry();
                                    on_save();
                                }}><Plus size="1em" /></button
                            >
                        </div>
                    </label>
                </div>
            </div>
        {:else if tab === 'security'}
            <div class="space-y-6 animate-in fade-in duration-300">
                <section class="space-y-4">
                    <h2
                        class="text-lg font-bold flex items-center gap-2 border-b border-surface-500/30 pb-2"
                    >
                        <Fingerprint size="1.2em" class="text-primary-500" />
                        Status & Security
                    </h2>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <label
                            class="flex items-center space-x-3 cursor-pointer p-3 rounded-lg bg-surface-500/5 border border-surface-500/10 transition-colors hover:bg-surface-500/10"
                        >
                            <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 access to this entry</span
                                >
                            </div>
                        </label>
                        <label
                            class="flex items-center space-x-3 cursor-pointer p-3 rounded-lg bg-surface-500/5 border border-surface-500/10 transition-colors hover:bg-surface-500/10"
                        >
                            <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>
                        <label
                            class="flex items-center space-x-3 cursor-pointer p-3 rounded-lg bg-surface-500/5 border border-surface-500/10 transition-colors hover:bg-surface-500/10"
                        >
                            <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"
                                    >Star or pin to top</span
                                >
                            </div>
                        </label>
                        <div
                            class="flex items-center justify-between p-3 rounded-lg bg-surface-500/5 border border-surface-500/10"
                        >
                            <div class="flex flex-col">
                                <span class="font-bold text-sm">Sort Order</span
                                >
                                <span class="text-xs opacity-60"
                                    >Manual list position</span
                                >
                            </div>
                            <div class="flex items-center gap-2">
                                <button
                                    type="button"
                                    class="btn-icon btn-icon-sm preset-tonal-surface"
                                    onclick={() => {
                                        tmp_entry_obj.sort =
                                            (tmp_entry_obj.sort ?? 0) - 1;
                                        handle_update_entry();
                                        on_save();
                                    }}><Minus size="1em" /></button
                                >
                                <span
                                    class="font-mono font-bold w-8 text-center text-lg"
                                    >{tmp_entry_obj.sort ?? 0}</span
                                >
                                <button
                                    type="button"
                                    class="btn-icon btn-icon-sm preset-tonal-surface"
                                    onclick={() => {
                                        tmp_entry_obj.sort =
                                            (tmp_entry_obj.sort ?? 0) + 1;
                                        handle_update_entry();
                                        on_save();
                                    }}><Plus size="1em" /></button
                                >
                            </div>
                        </div>
                    </div>
                </section>

                <section class="space-y-4">
                    <h4 class="text-xs font-bold uppercase opacity-50">
                        Privacy Flags
                    </h4>
                    <AE_Object_Flags
                        bind:obj={tmp_entry_obj}
                        on_toggle={() => {
                            handle_update_entry();
                            on_save();
                        }}
                        hide_alert={journal?.cfg_json?.hide_btn_alert}
                        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={journal?.cfg_json?.hide_btn_template}
                    />
                </section>

                {#if tmp_entry_obj.private && !tmp_entry_obj.content && tmp_entry_obj.content_encrypted}
                    <section class="pt-8 border-t border-error-500/20">
                        <div
                            class="bg-error-500/10 p-4 rounded-lg border border-error-500/30"
                        >
                            <h4
                                class="text-error-500 font-bold flex items-center gap-2 mb-2"
                            >
                                <RefreshCcw size="1.2em" /> Disaster Recovery
                            </h4>
                            <p class="text-xs opacity-70 mb-4 italic">
                                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}

                <section class="pt-12">
                    <button
                        type="button"
                        class="btn btn-sm preset-tonal-error w-full"
                        onclick={() => {
                            alert('Delete logic handled in parent component');
                        }}
                    >
                        <Trash2 size="1.1em" class="mr-2" /> Delete Entry
                    </button>
                </section>
            </div>
        {:else if tab === 'json'}
            <div class="h-full min-h-[400px]">
                <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/30"
                />
            </div>
        {/if}
    </div>

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