<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 from '$lib/elements/element_ae_obj_field_editor.svelte';
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 {
    Archive,
    BookOpen,
    Building2,
    Check,
    Eye,
    EyeOff,
    FingerprintPattern,
    IdCard,
    Key,
    LoaderCircle,
    Mail,
    Save,
    Star,
    Tag,
    ToggleLeft,
    ToggleRight,
    TriangleAlert,
    User,
    UserRound
} from '@lucide/svelte';
// 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/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);
    }
});

// .get() uses the primary key (id), which V3 never populates — always use .where().equals().first()
let lq__person_obj = $derived(
    liveQuery(() => db_core.person.where('person_id').equals(person_id).first())
);

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
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <IdCard size="1em" />
                External ID:
                <span class="font-bold">
                    {@html $lq__person_obj.external_id ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor>
        </li>
        <li class:hidden={!$ae_loc.trusted_access || !$ae_loc.edit_mode}>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <FingerprintPattern size="1em" />
                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>
        </li>

        <li>
            <User size="1em" />

            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <span class="font-bold">
                    {@html $lq__person_obj.given_name ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <span class="font-bold">
                    {@html $lq__person_obj.family_name ?? ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor>
        </li>
        <li>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <Mail size="1em" />
                <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>
        </li>
        <li>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <Building2 size="1em" />
                <span class="font-bold">
                    {@html $lq__person_obj.affiliations ??
                        'affiliations' + ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor>
        </li>
        <li>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <Tag size="1em" />
                <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>
        </li>
        <li>
            <Element_ae_obj_field_editor
                object_type={'person'}
                object_id={$lq__person_obj.person_id}
                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,
                        log_lvl: 1
                    })}>
                <UserRound size="1em" />
                Passcode:
                <span class="font-bold">
                    {@html $lq__person_obj.passcode ??
                        'passcode' + ae_snip.html__not_set}
                </span>
            </Element_ae_obj_field_editor>
        </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 core_func.update_ae_obj__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        data_kv: { hide: !$lq__person_obj?.hide }
                    });
                    core_func.load_ae_obj_id__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        log_lvl: 1
                    });
                }}
                class="btn btn-sm preset-tonal-warning">
                {#if $ae_loc.trusted_access}
                    {#if $lq__person_obj?.hide}
                        <Eye size="1em" class="m-1" /> Unhide?
                    {:else}
                        <EyeOff size="1em" class="m-1" /> Hide?
                    {/if}
                {:else}
                    <Archive size="1em" class="m-1" />
                    {$lq__person_obj?.hide ? 'Unarchive' : '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 core_func.update_ae_obj__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        data_kv: { enable: !$lq__person_obj?.enable }
                    });
                    core_func.load_ae_obj_id__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        log_lvl: 1
                    });
                }}
                class="btn btn-sm preset-tonal-warning">
                {#if $ae_loc.trusted_access}
                    {#if $lq__person_obj?.enable}
                        <ToggleRight size="1em" class="m-1" /> Disable?
                    {:else}
                        <ToggleLeft size="1em" class="m-1" /> Enable?
                    {/if}
                {:else if $lq__person_obj?.enable}
                    <ToggleRight size="1em" class="m-1" /> Disable
                {:else}
                    <ToggleLeft size="1em" class="m-1" /> 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 core_func.update_ae_obj__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        data_kv: { priority: !$lq__person_obj?.priority }
                    });
                    core_func.load_ae_obj_id__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        log_lvl: 1
                    });
                }}
                class="btn btn-sm preset-tonal-warning">
                <Star size="1em" class="m-1" />
                {#if $ae_loc.trusted_access}
                    {$lq__person_obj?.priority ? 'Not Priority?' : 'Priority?'}
                {:else}
                    {$lq__person_obj?.priority ? 'Not Priority' : '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 core_func.update_ae_obj__person({
                        api_cfg: $ae_api,
                        person_id: $lq__person_obj?.person_id,
                        data_kv: { 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,
                        log_lvl: 1
                    });
                }}
                class="btn btn-sm preset-tonal-warning">
                <Key size="1em" class="m-1" />
                {#if $ae_loc.trusted_access}
                    {$lq__person_obj?.allow_auth_key
                        ? 'Not Allow Auth Key?'
                        : 'Allow Auth Key?'}
                {:else}
                    {$lq__person_obj?.allow_auth_key
                        ? 'Not Allow Auth Key'
                        : 'Allow Auth Key'}
                {/if}
            </button>
        </li>

        <li>
            <div class="label person__data_json space-y-4">
                <label for="person__data_json" class="label">
                    <BookOpen size="1em" />
                    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}
                    <Check size="1em" class="text-green-500" />
                {:else}
                    <TriangleAlert size="1em" class="text-red-500" />
                    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,
                                data_kv: person_data,
                                log_lvl: 0
                            })
                            .then(function (update_result) {
                                // console.log(update_result);
                                // return update_result;
                            });
                    }}>
                    {#await ae_promises.update__person_obj}
                        <LoaderCircle size="1em" class="mx-1 animate-spin" />
                    {:then}
                        {#if ae_tmp.value__data_json == $lq__person_obj.data_json}
                            <Check size="1em" class="mx-1" />
                        {:else}
                            <Save size="1em" class="mx-1" />
                        {/if}
                    {/await}
                    Save JSON
                </button>
            </div>
        </li>
    </ul>
{/if}
