<script lang="ts">
    interface Props {
        person_id: string;
        display_mode?: string; // 'default', 'compact', 'minimal', 'launcher'
        log_lvl?: number;
    }

    let { person_id, display_mode = 'default', log_lvl = 0 }: Props = $props();

    console.log(`ae_core person_view.svelte`);

    import { liveQuery } from 'dexie';

    import type { key_val } from '$lib/stores/ae_stores';
    import { ae_util } from '$lib/ae_utils/ae_utils';
    import Element_ae_obj_field_editor_v3 from '$lib/elements/element_ae_obj_field_editor_v3.svelte';
    import { api } from '$lib/api/api';

    import { core_func } from '$lib/ae_core/ae_core_functions';
    import {
        ae_snip,
        ae_loc,
        ae_sess,
        ae_api,
        ae_trig,
        slct,
        slct_trigger
    } from '$lib/stores/ae_stores';
    import { db_core } from '$lib/ae_core/db_core';
    // import { db_events } from "$lib/db_events";
    // import { events_loc, events_sess, events_slct, events_trigger } from '$lib/stores/ae_events_stores';
    // import { events_func } from '$lib/ae_events_functions';

    let ae_placeholder_li: key_val = {};
    let ae_promises: key_val = $state({}); // Promise<any>;
    let ae_tmp: key_val = $state({});


    $effect(() => {
        if (log_lvl) {
            console.log(`person_id:`, person_id);
        }
    });

    let lq__person_obj = $derived(
        liveQuery(async () => {
            let results = await db_core.person.get(person_id);
            return results;
        })
    );

    ae_tmp.value__data_json = null;
    $effect(() => {
        if ($lq__person_obj?.data_json && ae_tmp.value__data_json === null) {
            ae_tmp.value__data_json = JSON.stringify($lq__person_obj.data_json, null, 4);
            // ae_tmp.value__data_json = JSON.parse(JSON.stringify($lq__person_obj.data_json));
            // JSON.stringify(jsObj, null, 4);
        }
    });

    ae_tmp.valid__data_json = null;
    $effect(() => {
        if (ae_tmp.value__data_json && ae_tmp.value__data_json.length) {
            console.log(`ae_tmp.value__data_json.length:`, ae_tmp.value__data_json.length);

            try {
                JSON.parse(ae_tmp.value__data_json);
                ae_tmp.valid__data_json = true;
            } catch (e) {
                ae_tmp.valid__data_json = false;
                console.error(`JSON.parse error:`, e);
            }
        }
    });

    // let tmp_agree = false;
    // let tmp_opt_out: key_val = {
    //     audio: false,
    //     video: false,
    //     transcription_and_publication: false,
    //     publication_in_app: false
    // };
</script>

{#if $lq__person_obj}
    <h2 class="h3">
        Person Details for:<br />
        <strong>
            "{$lq__person_obj.full_name}"
        </strong>
    </h2>

    <ul class="space-y-2 px-4">
        <li class:hidden={!$ae_loc.trusted_access || !$ae_loc.edit_mode}>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'external_id'}
                field_type={'text'}
                current_value={$lq__person_obj.external_id}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-id-card"></span>
                External ID:
                <span class="font-bold">
                    {@html $lq__person_obj.external_id ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>
        <li class:hidden={!$ae_loc.trusted_access || !$ae_loc.edit_mode}>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'external_sys_id'}
                field_type={'text'}
                current_value={$lq__person_obj.external_sys_id}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-fingerprint"></span>
                External System ID:
                <span class="font-bold">
                    {@html $lq__person_obj.external_sys_id ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>

        <li>
            <span class="fas fa-user"></span>

            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'given_name'}
                field_type={'text'}
                current_value={$lq__person_obj.given_name}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="font-bold">
                    {@html $lq__person_obj.given_name ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'family_name'}
                field_type={'text'}
                current_value={$lq__person_obj.family_name}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="font-bold">
                    {@html $lq__person_obj.family_name ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>
        <li>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'primary_email'}
                field_type={'text'}
                current_value={$lq__person_obj.primary_email}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-envelope"></span>
                <span class="font-bold">
                    {#if $lq__person_obj.primary_email}
                        <a
                            href="mailto:{$lq__person_obj?.primary_email}"
                            class="text-blue-500 underline hover:text-blue-800"
                            title="Person's primary email address"
                        >
                            {@html $lq__person_obj.primary_email ?? 'email' + ae_snip.html__not_set}
                        </a>
                    {:else}
                        email {@html ae_snip.html__not_set}
                    {/if}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>
        <li>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'affiliations'}
                field_type={'text'}
                current_value={$lq__person_obj.affiliations}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-building"></span>
                <span class="font-bold">
                    {@html $lq__person_obj.affiliations ?? 'affiliations' + ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>
        <li>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'professional_title'}
                field_type={'text'}
                current_value={$lq__person_obj.professional_title}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-user-tag"></span>
                <span class="font-bold">
                    {@html $lq__person_obj.professional_title &&
                    $lq__person_obj.professional_title.length
                        ? $lq__person_obj.professional_title
                        : 'professional title' + ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>
        <li>
            <Element_ae_obj_field_editor_v3
                object_type={'person'}
                object_id={$lq__person_obj.person_id_random}
                field_name={'passcode'}
                field_type={'text'}
                current_value={$lq__person_obj.passcode}
                allow_null={true}
                on_success={() => core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 })}
            >
                <span class="fas fa-user-secret"></span>
                Passcode:
                <span class="font-bold">
                    {@html $lq__person_obj.passcode ?? 'passcode' + ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor_v3>
        </li>

        <li hidden={!$ae_loc.trusted_access}>
            <!-- Show/Hide -->
            {#if $ae_loc.trusted_access}
                <span class="text-sm">{$lq__person_obj?.hide ? 'Hidden' : 'Not Hidden'}</span>
            {/if}
            <button
                type="button"
                onclick={async () => {
                    await api.update_ae_obj_v3({ api_cfg: $ae_api, obj_type: 'person', obj_id: $lq__person_obj?.person_id_random, fields: { hide: !$lq__person_obj?.hide } });
                    core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 });
                }}
                class="btn btn-sm preset-tonal-warning"
            >
                {#if $ae_loc.trusted_access}
                    {@html $lq__person_obj?.hide
                        ? '<span class="fas fa-eye m-1"></span> Unhide?'
                        : '<span class="fas fa-eye-slash m-1"></span> Hide?'}
                {:else}
                    {@html $lq__person_obj?.hide
                        ? '<span class="fas fa-archive m-1"></span> Unarchive'
                        : '<span class="fas fa-archive m-1"></span> Archive'}
                {/if}
            </button>

            <!-- Enable/Disable -->
            {#if $ae_loc.trusted_access}
                <span class="text-sm">{$lq__person_obj?.enable ? 'Enabled' : 'Disabled'}</span>
            {/if}
            <button
                type="button"
                onclick={async () => {
                    await api.update_ae_obj_v3({ api_cfg: $ae_api, obj_type: 'person', obj_id: $lq__person_obj?.person_id_random, fields: { enable: !$lq__person_obj?.enable } });
                    core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 });
                }}
                class="btn btn-sm preset-tonal-warning"
            >
                {#if $ae_loc.trusted_access}
                    {@html $lq__person_obj?.enable
                        ? '<span class="fas fa-toggle-on m-1"></span> Disable?'
                        : '<span class="fas fa-toggle-off m-1"></span> Enable?'}
                {:else}
                    {@html $lq__person_obj?.enable
                        ? '<span class="fas fa-toggle-on m-1"></span> Disable'
                        : '<span class="fas fa-toggle-off m-1"></span> Enable'}
                {/if}
            </button>

            <!-- Priority/Not -->
            {#if $ae_loc.trusted_access}
                <span class="text-sm">{$lq__person_obj?.priority ? 'Priority' : 'Not Priority'}</span>
            {/if}
            <button
                type="button"
                onclick={async () => {
                    await api.update_ae_obj_v3({ api_cfg: $ae_api, obj_type: 'person', obj_id: $lq__person_obj?.person_id_random, fields: { priority: !$lq__person_obj?.priority } });
                    core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 });
                }}
                class="btn btn-sm preset-tonal-warning"
            >
                {#if $ae_loc.trusted_access}
                    {@html $lq__person_obj?.priority
                        ? '<span class="fas fa-star m-1"></span> Not Priority?'
                        : '<span class="fas fa-star m-1"></span> Priority?'}
                {:else}
                    {@html $lq__person_obj?.priority
                        ? '<span class="fas fa-star m-1"></span> Not Priority'
                        : '<span class="fas fa-star m-1"></span> Priority'}
                {/if}
            </button>

            <!-- Allow Auth Key/Not -->
            {#if $ae_loc.trusted_access}
                <span class="text-sm">{$lq__person_obj?.allow_auth_key ? 'Allow Auth Key' : 'Not Allow Auth Key'}</span>
            {/if}
            <button
                type="button"
                onclick={async () => {
                    await api.update_ae_obj_v3({ api_cfg: $ae_api, obj_type: 'person', obj_id: $lq__person_obj?.person_id_random, fields: { allow_auth_key: !$lq__person_obj?.allow_auth_key } });
                    core_func.load_ae_obj_id__person({ api_cfg: $ae_api, person_id: $lq__person_obj?.person_id_random, log_lvl: 1 });
                }}
                class="btn btn-sm preset-tonal-warning"
            >
                {#if $ae_loc.trusted_access}
                    {@html $lq__person_obj?.allow_auth_key
                        ? '<span class="fas fa-key m-1"></span> Not Allow Auth Key?'
                        : '<span class="fas fa-key m-1"></span> Allow Auth Key?'}
                {:else}
                    {@html $lq__person_obj?.allow_auth_key
                        ? '<span class="fas fa-key m-1"></span> Not Allow Auth Key'
                        : '<span class="fas fa-key m-1"></span> Allow Auth Key'}
                {/if}
            </button>
        </li>

        <li>
            <div class="label person__data_json space-y-4">
                <label for="person__data_json" class="label">
                    <span class="fas fa-book"></span>
                    Person JSON Data
                    <span class="text-sm text-gray-500"> (no character limit) </span>
                </label>

                <textarea
                    name="data_json"
                    id="person__data_json"
                    disabled={!$ae_loc.administrator_access}
                    class="textarea ae_value person__data_json font-mono"
                    class:preset-tonal-error={ae_tmp.value__data_json &&
                    ae_tmp.value__data_json.length > 600
                        ? true
                        : false}
                    required
                    rows="8"
                    cols="70"
                    bind:value={ae_tmp.value__data_json}
                    placeholder="Enter data_json here"
                ></textarea>
                <!-- {/if} -->
            </div>

            <p>
                JSON length: {ae_tmp.value__data_json
                    ? ae_util.number_w_commas(ae_tmp.value__data_json.length)
                    : 0} characters

                {#if ae_tmp.valid__data_json}
                    <span class="fas fa-check text-green-500"></span>
                {:else}
                    <span class="fas fa-exclamation-triangle text-red-500"></span>
                    Invalid JSON
                {/if}
            </p>

            <div class="flex flex-wrap gap-2 p-1">
                <button
                    type="button"
                    class="btn btn-md preset-tonal-primary hover:preset-filled-primary-500"
                    disabled={!$ae_loc.trusted_access ||
                        ae_tmp.value__data_json == $lq__person_obj.data_json}
                    onclick={() => {
                        console.log('*** Save button clicked ***');

                        // We need to parse the JSON string into an object. In the future this should be dynamic and allow for basic key_val object.
                        let data_json_obj = JSON.parse(ae_tmp.value__data_json);

                        let person_data = {
                            data_json: data_json_obj
                        };

                        ae_promises.update__person_obj = core_func
                            .update_ae_obj__person({
                                api_cfg: $ae_api,
                                person_id: $lq__person_obj.person_id_random,
                                data_kv: person_data,
                                log_lvl: 0
                            })
                            .then(function (update_result) {
                                // console.log(update_result);
                                // return update_result;
                            });
                    }}
                >
                    {#await ae_promises.update__person_obj}
                        <span class="fas fa-spinner fa-spin mx-1"></span>
                    {:then}
                        {#if ae_tmp.value__data_json == $lq__person_obj.data_json}
                            <span class="fas fa-check mx-1"></span>
                        {:else}
                            <span class="fas fa-save mx-1"></span>
                        {/if}
                    {/await}
                    Save JSON
                </button>
            </div>
        </li>
    </ul>
{/if}
