<script lang="ts">
// *** Import Svelte core
import { onMount } from 'svelte';

// *** Import Aether core variables and functions
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { core_func } from '$lib/ae_core/ae_core_functions';
import { liveQuery } from 'dexie';
import { db_lookups } from '$lib/ae_core/db_lookups';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
import { idaa_loc, idaa_sess, idaa_slct } from '$lib/stores/ae_idaa_stores';
import { archives_func } from '$lib/ae_archives/ae_archives_functions';

import AE_Comp_Editor_TipTap from '$lib/elements/element_editor_tiptap.svelte';

interface Props {
    log_lvl?: number;
    lq__archive_obj: any;
}

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

let create_archive_obj_promise: any;
let delete_archive_obj_promise: any;
let update_archive_obj_promise: any;
let upload__hosted_file_obj_promise: any;
let prom_api__archive_obj: any;
let prom_api__archive_obj__hosted_file: any;

let description_new_html = $state($idaa_slct.archive_obj?.description ?? '');
let description_changed = $state(false);
let notes_new_html = $state($idaa_slct.archive_obj?.notes ?? '');
let notes_changed = $state(false);
let disable_submit_btn = true;

// Timezone lookup — reactive IDB query; background refresh handled by liveQuery + TTL
// Sort: sort DESC (higher = first, NULL=0 last), then name ASC — matches Aether backend convention.
const lq__lu_time_zone = liveQuery(() =>
    db_lookups.lu_time_zone.toArray().then((arr) =>
        arr.sort((a, b) => {
            const s_diff = Number(b['sort'] ?? 0) - Number(a['sort'] ?? 0);
            if (s_diff !== 0) return s_diff;
            return (a.name ?? '').localeCompare(b.name ?? '');
        })
    )
);

onMount(() => {
    // Trigger background IDB refresh if stale/empty; liveQuery reacts automatically
    core_func.load_ae_obj_li__time_zone({ api_cfg: $ae_api, log_lvl });
});

function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}

async function handle_submit_form(event: any) {
    if (log_lvl) {
        console.log('*** handle_submit_form() ***');
        console.log(event.currentTarget);
    }

    disable_submit_btn = true;

    let form_data = new FormData(event.currentTarget);
    console.log(form_data);

    let archive_di = ae_util.extract_prefixed_form_data({
        prefix: null,
        form_data: form_data,
        trim_values: true,
        bool_tf_str: true,
        log_lvl: 0
    });
    console.log(archive_di);

    let archive_do: key_val = {};

    if (!$idaa_slct.archive_id) {
        archive_do['account_id_random'] = $ae_loc.account_id;
        // archive_do['enable'] = true;
    }

    archive_do['name'] = archive_di.name;

    // Check if the description_new_html exists and is a string
    if (typeof description_new_html === 'string') {
        console.log('New description is a string');
        archive_do['description'] = description_new_html;
    } else {
        console.log('New description is not a string. Do nothing.');
        // archive_do['description'] = event_meeting_fd.description;
    }

    let date_time_str = null;
    let date_part = archive_di.original_datetime_date.trim();
    let time_part = archive_di.original_datetime_time.trim();
    if (date_part && time_part) {
        date_time_str = `${date_part} ${time_part}`;
    } else if (date_part) {
        date_time_str = `${date_part}T00:00:00`;
    } else if (time_part) {
        // date_time_str = `${time_part}`;
        date_time_str = false;
    }
    archive_do['original_datetime'] = date_time_str;

    archive_do['original_timezone'] = archive_di.original_timezone;

    archive_do['original_location'] = archive_di.original_location;

    archive_do['original_url'] = archive_di.original_url;
    archive_do['original_url_text'] = archive_di.original_url_text;

    if (archive_di.cfg_json) {
        try {
            archive_do['cfg_json'] = JSON.parse(archive_di.cfg_json);
        } catch (error) {
            console.log('Error parsing JSON:', error);
        }
    } else {
        // archive_do['cfg_json'] = {};
    }

    archive_do['hide'] = archive_di.hide;
    archive_do['priority'] = archive_di.priority;
    if (archive_di.sort) {
        archive_do['sort'] = Number(archive_di.sort);
    } else {
        archive_do['sort'] = null;
    }
    if (archive_di.group) {
        archive_do['group'] = archive_di.group;
    } else {
        archive_do['group'] = null;
    }

    // console.log(`archive_di.enable = ${archive_di.enable}`);
    archive_do['enable'] = !!archive_di.enable;

    // Check if the notes_new_html exists and is a string
    if (typeof notes_new_html === 'string') {
        console.log('New notes is a string');
        archive_do['notes'] = notes_new_html;
    } else {
        console.log('New notes is not a string. Do nothing.');
        // archive_do['notes'] = event_meeting_fd.notes;
    }

    console.log(archive_do);

    if (!$idaa_slct.archive_id) {
        prom_api__archive_obj = archives_func
            .create_ae_obj__archive({
                api_cfg: $ae_api,
                account_id: $ae_loc.account_id,
                data_kv: archive_do,
                log_lvl: log_lvl
            })
            .then(async function (archive_obj_create_result) {
                if (!archive_obj_create_result) {
                    console.log('The result was null or false.');
                    return false;
                }

                $idaa_slct.archive_id =
                    archive_obj_create_result.archive_id;
                $idaa_slct.archive_obj = archive_obj_create_result;

                return update_archive_obj_promise;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            })
            .finally(() => {
                disable_submit_btn = false;
            });

        return create_archive_obj_promise;
    } else {
        prom_api__archive_obj = archives_func
            .update_ae_obj__archive({
                api_cfg: $ae_api,
                archive_id: $idaa_slct.archive_id,
                data_kv: archive_do,
                log_lvl: log_lvl
            })
            .then(function (archive_obj_update_result) {
                if (!archive_obj_update_result) {
                    console.log('The result was null or false.');
                    return false;
                }

                return archive_obj_update_result;
            })
            .catch(function (error: any) {
                console.log('Something went wrong.');
                console.log(error);
                return false;
            })
            .finally(() => {
                // We need to do all of this since the DB object has changed and the SLCT object does automatically update (yet...??? Svelte 5?).
                // $idaa_slct.archive_obj = await $lq__archive_obj;

                // $idaa_slct.archive_id = null;
                // $idaa_slct.archive_obj = {};
                $idaa_sess.archives.show__modal_edit__archive_id = false;
            });

        return prom_api__archive_obj;
    }
}

// Updated 2024-11-15
async function handle_delete_archive_obj({
    archive_id,
    method = 'disable'
}: {
    archive_id: string;
    method?: 'delete' | 'soft_delete' | 'disable' | 'hide';
}) {
    if (log_lvl) {
        console.log('*** handle_delete_archive_obj() ***');
    }

    prom_api__archive_obj = archives_func
        .delete_ae_obj_id__archive({
            api_cfg: $ae_api,
            archive_id: archive_id,
            method: method,
            log_lvl: log_lvl
        })
        .then(function (archive_obj_delete_result) {
            $idaa_sess.archives.show__modal_edit__archive_id = false;
            $idaa_sess.archives.show__modal_view__archive_id = false;
            $idaa_sess.archives.show__modal_edit__archive_content_id = false;
            $idaa_sess.archives.show__modal_view__archive_content_id = false;
        })
        .catch(function (error: any) {
            console.log(
                'The result was null or false when trying to delete.',
                error
            );
        })
        .finally(() => {
            // $idaa_sess.recovery_meetings.show__modal_edit = false;
            $idaa_slct.archive_id = null;
            $idaa_slct.archive_obj = null;
            $idaa_slct.archive_content_id = null;
            $idaa_slct.archive_content_obj = null;
        });

    return prom_api__archive_obj;
}
</script>

<section
    class="
        svelte_component ae_section ae_edit archive_obj edit__archive_obj
        preset-filled-surface-50-950 preset-outlined-warning-400-600
        space-y-2
        rounded-md p-2
        "
    class:ae_create={!$idaa_slct.archive_id}
    bind:clientHeight={$ae_loc.iframe_height_modal_body}>
    <form onsubmit={prevent_default(handle_submit_form)} class="space-y-1">
        <!-- <h2 class="h2">Archive</h2> -->

        <div
            class="ae_section archive__general space-y-2 rounded border border-gray-200 p-2">
            <div>
                <label for="name" class="w-full">
                    <span class="text-sm font-semibold"> Name of Archive </span>
                    <input
                        type="text"
                        id="name"
                        name="name"
                        required
                        max="20"
                        value={$idaa_slct.archive_obj.name
                            ? $idaa_slct.archive_obj.name
                            : 'Testing!'}
                        autocomplete="off"
                        class="
                    input preset-tonal-surface
                    hover:preset-filled-surface-100-900 form-control
                    w-full
                    "
                        placeholder="Name of Archive" />
                </label>
            </div>

            <label for="description" class="ae_label w-full">
                <span class="legend text-sm font-semibold"> Description </span>
                <AE_Comp_Editor_TipTap
                    bind:content={description_new_html}
                    class_li="preset-tonal-surface hover:preset-filled-surface-100-900"
                    placeholder="Your archive description here..." />
            </label>
        </div>

        <div
            class="ae_section archive__original space-y-2 rounded border border-gray-200 p-2">
            <h3 class="h3">Original</h3>

            <label for="original_datetime"
                >Original Date/Time
                <input
                    type="date"
                    id="original_datetime_date"
                    name="original_datetime_date"
                    value={$idaa_slct.archive_obj.original_datetime
                        ? ae_util.iso_datetime_formatter(
                              $idaa_slct.archive_obj.original_datetime,
                              'date_iso'
                          )
                        : ''}
                    placeholder="YYYY-MM-DD"
                    class="input w-48" />
                <input
                    type="time"
                    id="original_datetime_time"
                    name="original_datetime_time"
                    value={$idaa_slct.archive_obj.original_datetime
                        ? ae_util.iso_datetime_formatter(
                              $idaa_slct.archive_obj.original_datetime,
                              'time_iso'
                          )
                        : ''}
                    placeholder="HH:MM AM/PM"
                    class="input w-48" />
            </label>

            <fieldset class="flex_row flex_gap_md flex_justify_around">
                <label for="original_timezone"
                    >Original Timezone
                    {#if ($lq__lu_time_zone ?? []).length}
                        <select
                            name="original_timezone"
                            id="original_timezone"
                            required
                            value={$idaa_slct.archive_obj.original_timezone
                                ? $idaa_slct.archive_obj.original_timezone
                                : $ae_loc.current_timezone}
                            class="select w-56"
                            title="Select the original timezone">
                            <option value="">-- None --</option>
                            {#each $lq__lu_time_zone ?? [] as lu_timezone (lu_timezone.name)}
                                <option value={lu_timezone.name}>
                                    {lu_timezone.name}
                                </option>
                            {/each}
                        </select>
                    {:else}
                        <input
                            type="text"
                            name="timezone"
                            value={$idaa_slct.archive_obj.original_timezone
                                ? $idaa_slct.archive_obj.original_timezone
                                : $ae_loc.current_timezone}
                            class="input w-56" />
                    {/if}
                </label>
            </fieldset>

            <!-- <label for="original_timezone">Original Timezone
            <input type="text" id="original_timezone" name="original_timezone" value={($idaa_slct.archive_obj.original_timezone ? $idaa_slct.archive_obj.original_timezone : $ae_loc.current_timezone)} placeholder="Timezone" list="timezones">
            <datalist id="timezones">
                <option value="UTC">UTC</option>
                <option value="America/New_York">America/New York</option>
                <option value="America/Chicago">America/Chicago</option>
                <option value="America/Denver">America/Denver</option>
                <option value="America/Phoenix">America/Phoenix</option>
                <option value="America/Los_Angeles">America/Los Angeles</option>
                <option value="America/Anchorage">America/Anchorage</option>
                <option value="America/Adak">America/Adak</option>
                <option value="Pacific/Honolulu">Pacific/Honolulu</option>
                <option value="Pacific/Midway">Pacific/Midway</option>
                <option value="US/Eastern">US/Eastern</option>
                <option value="US/Central">US/Central</option>
                <option value="US/Mountain">US/Mountain</option>
                <option value="US/Pacific">US/Pacific</option>
                <option value="US/Alaska">US/Alaska</option>
                <option value="US/Hawaii">US/Hawaii</option>
                <option value="US/Samoa">US/Samoa</option>
                <option value="US/Aleutian">US/Aleutian</option>
                <option value="US/Arizona">US/Arizona</option>
                <option value="US/Michigan">US/Michigan</option>
            </datalist>
        </label> -->

            <label for="original_location"
                >Original Location
                <input
                    type="text"
                    id="original_location"
                    name="original_location"
                    value={$idaa_slct.archive_obj.original_location
                        ? $idaa_slct.archive_obj.original_location
                        : ''}
                    placeholder="Location"
                    class="input w-full" />
            </label>

            <label for="original_url"
                >Original URL
                <input
                    type="text"
                    id="original_url"
                    name="original_url"
                    max="255"
                    value={$idaa_slct.archive_obj.original_url
                        ? $idaa_slct.archive_obj.original_url
                        : ''}
                    placeholder="URL"
                    class="input w-full" />
            </label>

            <label for="original_url_text"
                >Original URL Text/Title
                <input
                    type="text"
                    id="original_url_text"
                    name="original_url_text"
                    max="255"
                    value={$idaa_slct.archive_obj.original_url_text
                        ? $idaa_slct.archive_obj.original_url_text
                        : ''}
                    placeholder="URL text or title"
                    class="input w-full" />
            </label>
        </div>

        <!-- <h3>Archiver's Options</h3> -->

        <!-- <fieldset class="">
        <legend class="">Official or Member Archive</legend>
        <div class="">
            <input type="radio" class="" id="group_official" name="group" value="official">
            <label for="group_official" class="">Archive as Official/Leadership</label>
        </div>
        <div class="">
            <input type="radio" class="" id="group_member" name="group" value="member" checked="">
            <label for="group_member" class="">Archive as Member</label>
        </div>
    </fieldset> -->

        <!-- <fieldset class="">
        <legend class="">Enable Comments</legend>
        <div class="">
            <input type="radio" class="" id="enable_comments_no" name="enable_comments" value="0">
            <label for="enable_comments_no" class="">No, do not allow comments</label>
        </div>
        <div class="">
            <input type="radio" class="" id="enable_comments_yes" name="enable_comments" value="1" checked>
            <label for="enable_comments_yes" class="">Yes, allow comments</label>
        </div>
    </fieldset> -->

        {#if $ae_loc.administrator_access}
            <textarea
                name="cfg_json"
                id="cfg_json"
                class="textarea w-full font-mono text-sm"
                rows={$idaa_slct.archive_obj.cfg_json?.length ?? 6}
                >{JSON.stringify(
                    $idaa_slct.archive_obj.cfg_json,
                    null,
                    2
                )}</textarea>
        {/if}

        {#if $ae_loc.trusted_access}
            <!-- BEGIN: section archive__admin_options -->
            <div
                class="bg-surface-100-900 border-error-400 space-y-3 rounded-md border p-3">
                <button
                    type="button"
                    class="flex w-full flex-row items-center gap-2 text-left"
                    onclick={() => {
                        $idaa_loc.archives.show__admin_options =
                            !$idaa_loc.archives.show__admin_options;
                    }}>
                    <span
                        class="fas fa-{$idaa_loc.archives.show__admin_options
                            ? 'caret-down'
                            : 'caret-right'} text-xs opacity-60"></span>
                    <h3
                        class="text-surface-600-400 flex w-full items-center gap-2 text-lg font-semibold">
                        <span class="fas fa-cogs"></span>
                        Admin Options
                    </h3>
                </button>

                <div
                    class="space-y-3"
                    class:hidden={!$idaa_loc.archives.show__admin_options}>
                    <span
                        class="flex w-full flex-col flex-wrap items-center justify-center gap-2 md:flex-row md:justify-stretch">
                        <span
                            class="flex grow flex-row flex-wrap items-center justify-evenly gap-1">
                            <fieldset
                                class="form-check flex flex-row items-center justify-center gap-1">
                                <legend
                                    class="legend form-check-label text-sm font-semibold"
                                    >Hide</legend>
                                <div>
                                    <input
                                        type="radio"
                                        id="hide_yes"
                                        name="hide"
                                        value={true}
                                        bind:group={$idaa_slct.archive_obj.hide}
                                        class="radio form-check-input" />
                                    <label for="hide_yes">Yes</label>
                                </div>
                                <div>
                                    <input
                                        type="radio"
                                        id="hide_no"
                                        name="hide"
                                        value={false}
                                        bind:group={$idaa_slct.archive_obj.hide}
                                        class="radio form-check-input" />
                                    <label for="hide_no">No</label>
                                </div>
                            </fieldset>

                            <fieldset
                                class="form-check flex flex-row items-center justify-center gap-1">
                                <legend
                                    class="legend form-check-label text-sm font-semibold"
                                    >Priority</legend>
                                <div>
                                    <input
                                        type="radio"
                                        id="priority_yes"
                                        name="priority"
                                        value={true}
                                        bind:group={
                                            $idaa_slct.archive_obj.priority
                                        }
                                        class="radio form-check-input" />
                                    <label for="priority_yes">Yes</label>
                                </div>
                                <div>
                                    <input
                                        type="radio"
                                        id="priority_no"
                                        name="priority"
                                        value={false}
                                        bind:group={
                                            $idaa_slct.archive_obj.priority
                                        }
                                        class="radio form-check-input" />
                                    <label for="priority_no">No</label>
                                </div>
                            </fieldset>
                        </span>

                        <span
                            class="
                    col-sm-1
                    flex grow flex-row flex-wrap items-center justify-evenly
                    gap-1
                    ">
                            <label
                                class="legend input-group text-sm font-semibold"
                                >Sort <input
                                    type="number"
                                    name="sort"
                                    value={$idaa_slct.archive_obj.sort}
                                    class="input preset-tonal-surface form-control w-24" /></label>

                            <label
                                class="legend input-group text-sm font-semibold"
                                >Group <input
                                    type="text"
                                    name="group"
                                    value={$idaa_slct.archive_obj.group ?? ''}
                                    max="100"
                                    class="input preset-tonal-surface form-control w-40" /></label>
                        </span>

                        {#if $ae_loc.administrator_access}
                            <span
                                class="flex grow flex-row flex-wrap items-center justify-evenly gap-1">
                                <fieldset
                                    class="align-center form-check flex flex-row items-center gap-1">
                                    <legend
                                        class="legend form-check-label text-sm font-semibold"
                                        >Enable</legend>
                                    <div>
                                        <input
                                            type="radio"
                                            id="enable_yes"
                                            name="enable"
                                            value={true}
                                            bind:group={
                                                $idaa_slct.archive_obj.enable
                                            }
                                            class="radio form-check-input" />
                                        <label for="enable_yes">Yes</label>
                                    </div>
                                    <div>
                                        <input
                                            type="radio"
                                            id="enable_no"
                                            name="enable"
                                            value={false}
                                            bind:group={
                                                $idaa_slct.archive_obj.enable
                                            }
                                            class="radio form-check-input" />
                                        <label for="enable_no">No</label>
                                    </div>
                                </fieldset>
                            </span>
                        {:else}
                            <input
                                type="hidden"
                                name="enable"
                                value={$idaa_slct.archive_obj.enable} />
                        {/if}
                    </span>

                    {#if $ae_loc.trusted_access}
                        <label for="notes" class="w-full">
                            <span
                                class="legend text-surface-600-400 text-sm font-semibold"
                                >Internal Staff Notes</span>
                            <AE_Comp_Editor_TipTap
                                bind:content={notes_new_html}
                                class_li="preset-tonal-surface preset-filled-surface-100-900"
                                placeholder="Internal notes for staff only. Not shown to the public." />
                        </label>
                    {/if}

                    <div class="text-sm text-gray-600 dark:text-gray-400">
                        {$lq__archive_obj?.updated_on
                            ? `DB Updated on: ${$lq__archive_obj?.updated_on}`
                            : ''}
                        {$idaa_slct.archive_obj?.updated_on
                            ? `SLCT Updated on: ${$idaa_slct.archive_obj?.updated_on}`
                            : ''}
                    </div>
                </div>
            </div>
            <!-- END: section archive__admin_options -->
        {/if}

        <div
            class="ae_section ae_options flex flex-row items-center justify-center gap-1">
            <button
                type="submit"
                class="
                novi_btn
                btn btn-md preset-tonal-primary preset-outlined-primary-800-200 hover:preset-filled-primary-200-800
                transition
                ">
                <span class="fas fa-check m-1"></span>
                Save Archive
            </button>

            {#if $idaa_slct.archive_id}
                <button
                    type="button"
                    onclick={() => {
                        if (
                            !confirm(
                                'Are you sure you want to delete this archive?'
                            )
                        ) {
                            return false;
                        }
                        handle_delete_archive_obj({
                            archive_id: $idaa_slct.archive_id
                        });
                    }}
                    class="
                novi_btn
                btn btn-sm
                preset-filled-warning-200-800 hover:preset-filled-error-200-800
                transition
                "
                    title="Disable this archive content">
                    <span class="fas fa-minus m-1"></span>
                    Delete
                </button>
            {/if}
        </div>
    </form>
</section>

<style>
</style>
