<script lang="ts">
/** @type {import('./$types').PageData} */
export let data: any;
// console.log(`ae_events_pres_mgmt event [slug] +page.svelte data:`, data);

import { onMount } from 'svelte';
import { goto, invalidate, pushState, replaceState } from '$app/navigation';

import { clipboard, FileDropzone, getModalStore, localStorageStore, ProgressRadial, RadioGroup, RadioItem, TabGroup, Tab, TabAnchor } from '@skeletonlabs/skeleton';

import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils';
import { api } from '$lib/api';
import Element_ae_crud from '$lib/element_ae_crud.svelte';

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

// Quickly save the data passed from the parent(s) to the Svelte stores, localStorage, and other.
$slct.account_id = data.account_id;
console.log(`$slct.account_id = `, $slct.account_id);
let ae_acct = data[$slct.account_id];
console.log(`ae_acct = `, ae_acct);

$events_slct.event_id = ae_acct.slct.event_id;
$events_slct.event_obj = ae_acct.slct.event_obj;
$events_slct.event_session_obj_li = ae_acct.slct.event_session_obj_li;

// import Leads_add_scan from './leads_add_scan.svelte';
// import Sessions_list from './sessions_list.svelte';
// import Leads_manage from './leads_manage.svelte';
// import Leads_payment from './leads_payment.svelte';

// let param_slug_event_id = data.params.slug;

let event_obj = liveQuery(
    () => db_events.events.get($events_slct.event_id)
    // () => db_events.events.get(param_slug_event_id)
    // () => db_events.events.toArray()
    // () => db_events.events
    //     .where('id_random')
    //     .equals($events_slct.event_id)
    //     // .orderBy('name')
    //     // .offset(10).limit(5)
    //     .toArray()
);

let event_obj_v2 = db_events.events.get($events_slct.event_id);


let load_obj_li_results: Promise<any>|key_val;
let search_submit_results: Promise<any>|key_val;

let ae_tmp: key_val = {};
let ae_triggers: key_val = {};

let ae_event_session_get_promise: Promise<any>;

// if (!$events_loc.leads.tab) {
//     $events_loc.leads.tab = {};
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }

// if (!$events_loc.leads.auth_exhibit_kv) {
//     $events_loc.leads.auth_exhibit_kv = {};
// }

// if ($events_loc.leads.auth_exhibit_kv && $events_loc.leads.auth_exhibit_kv[$events_slct.event_id]) {
//     console.log('Logged in using shared exhibit staff passcode.');

//     if ($events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key) {
//         console.log(`Using the license key: ${$events_loc.leads.auth_exhibit_kv[$events_slct.event_id].key}`);
//     } else {
//         console.log('License key (email) not used.');
//         $events_loc.leads.tab[$events_slct.event_id] = 'start';
//     }
// } else {
//     console.log('Not logged in using shared exhibit staff passcode.');
//     $events_loc.leads.tab[$events_slct.event_id] = 'start';
// }


onMount(() => {
    console.log('Events Event [slug]: +page.svelte');

    if (!$events_slct.event_id) {
        console.log(`No ID! Nothing to show. Try setting the ID again.`);
        $events_slct.event_id = $events_slct.event_id;
    }

});


// Updated 2024-06-12 late
$: if ($events_trigger == 'load__event_session_obj_li' && $events_slct.event_id) {
    console.log(`load__event_session_obj_li() $events_slct.event_id=${$events_slct.event_id}`);

    $events_trigger = null;

    if (!$events_sess.pres_mgmt.fulltext_search_qry_str || $events_sess?.pres_mgmt.fulltext_search_qry_str.length <= 1 ) {
        $events_slct.session_obj_li = [];
        // $events_sess.pres_mgmt.fulltext_search_qry_str = '';
    } else {

    // let type_code = $events_sess.pres_mgmt.search_badge_type_code;

    let search_str = $events_sess.pres_mgmt.fulltext_search_qry_str.trim();
    let search_method = 'lk'; // 'ft', 'lk', 'eq'
    let ft_search_str_new = '';
    let lk_search_str_new = '';

    if (search_method == 'ft') {
        // Add quotes around the search string to make it an exact match.
        ft_search_str_new = `${search_str}`;
        // ft_search_str_new = `"${search_str}"`;
    } else if (search_method == 'lk') {
        // Add a wildcard to the search string to make it a like match.
        lk_search_str_new = search_str.trim().replace(',', ' ').replace(';', ' ').replaceAll('  ', '%').replaceAll(' ', '%');
        lk_search_str_new = `%${lk_search_str_new}%`;
    }
    console.log(`"${search_str}"`);

    let params = {
        'qry__enabled': 'enabled',
        'qry__hidden': 'not_hidden',
        'qry__limit': 35,
    }

    if ($ae_loc.administrator_access) {
        params['qry__enabled'] = 'all';
        params['qry__hidden'] = 'all';
        params['qry__limit'] = 150;
    } else if ($ae_loc.trusted_access) {
        params['qry__enabled'] = 'enabled';
        params['qry__hidden'] = 'all';
        params['qry__limit'] = 75;
    } else {
        params['qry__enabled'] = 'enabled';
        params['qry__hidden'] = 'not_hidden';
        params['qry__limit'] = 35;
    }

    if ($events_sess.status_qry__search == 'loading') {
        console.log('*** $events_sess.status_qry__search == loading ***');

        setTimeout(() => {
            console.log("Delayed for X second.");

            $events_sess.status_qry__search = 'loading';

            search_submit_results = events_func.handle_search__event_session({
                api_cfg: $ae_api,
                event_id: $events_slct.event_id,
                // type_code: type_code,
                fulltext_search_qry_str: ft_search_str_new,
                ft_presenter_search_qry_str: null,
                like_search_qry_str: lk_search_str_new,
                like_presenter_search_qry_str: lk_search_str_new,
                // external_event_id: $events_loc.pres_mgmt.default__external_registration_id,
                params: params,
                try_cache: false,
                log_lvl: 1,
            })
            .then(function (search_results) {
                $events_slct.session_obj_li = search_results;
                console.log(search_results);
                $events_sess.status_qry__search = 'done';
            });
        }, 250);
    } else {
        console.log('*** $events_sess.status_qry__search != loading ***');

        $events_sess.status_qry__search = 'loading';

        search_submit_results = events_func.handle_search__event_session({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            // type_code: type_code,
            fulltext_search_qry_str: ft_search_str_new,
            ft_presenter_search_qry_str: null,
            like_search_qry_str: lk_search_str_new,
            like_presenter_search_qry_str: lk_search_str_new,
            // external_event_id: $events_loc.pres_mgmt.default__external_registration_id,
            params: params,
            try_cache: false,
            log_lvl: 1,
        })
        .then(function (search_results) {
            $events_slct.session_obj_li = search_results;
            console.log(search_results);
            $events_sess.status_qry__search = 'done';
        });
    }

    } // end if search string is valid
}




</script>


<section
    class="ae_events_pres_mgmt_event md:container h-full mx-auto flex flex-col items-center space-y-2 pt-0 pb-8"
    >


{#if $events_slct.event_id && $event_obj}
<h2 class="h3 text-center">{$event_obj.name}</h2>
<h3 class="h4 text-center">Presentation Management Hub</h3>
{/if}

<div class="variant-ghost-success my-2 p-2 rounded-md flex flex-row items-center">

<form
    on:submit|preventDefault={() => {
        $events_trigger = 'load__event_session_obj_li';
    }}
    autocomplete="off"
    class="form flex-grow flex flex-row flex-wrap gap-1 justify-center items-center w-full"
    >
    <button
        type="button"
        class="btn btn-sm variant-ghost-warning hover:variant-filled-warning transition-all mx-1"
        on:click={() => {
            $events_sess.pres_mgmt.fulltext_search_qry_str = '';
            $events_trigger = 'load__event_session_obj_li';
        }}
        >
        <!-- <span class="fas fa-backspace"></span> -->
        <!-- <span class="fas fa-broom"></span> -->
         <span class="fas fa-remove-format"></span>
        <!-- Clear text -->
    </button>

    <input
    type="search"
    placeholder="Search for a session"
    id="session_fulltext_search_qry_str"
    bind:value={$events_sess.pres_mgmt.fulltext_search_qry_str}
    class="input text-1xl hover:text-2xl font-bold font-mono w-80 transition-all mx-1"
    on:keyup={() => {
        if ($events_sess.pres_mgmt?.fulltext_search_qry_str && $events_sess.pres_mgmt.fulltext_search_qry_str.length >= 3) {
            $events_trigger = 'load__event_session_obj_li';
        }
    }}
    autofocus
    suggest="off"
    data-ignore="true"
    />

    <button
        type="submit"
        class="btn btn-lg variant-ghost-success hover:variant-filled-success text-2xl font-bold w-48 transition-all mx-1"
        on:click={() => {

        }}
        >
        {#if $events_sess.pres_mgmt.status_qry__search == 'loading'}
            <span class="fas fa-spinner fa-spin"></span>
        {:else }
            <!-- Nothing -->
        {/if}
        <span class="fas fa-search mx-1"></span>
        Search
    </button>
</form>

</div>





{#await load_obj_li_results}
    <span class="modal-loading">
        <span class="fas fa-spinner fa-spin"></span>
        <span class="loading-text">
            Loading...
        </span>
    </span>
{:then load_obj_li_results}
    {#if load_obj_li_results}
    <span class="fas fa-check text-green-500"></span>
    <span class="saved-text">
        Loaded
    </span>
    {/if}
{/await}


{#if $events_slct?.session_obj_li && $events_slct.session_obj_li.length > 0}
<section class="ae_h_scrollfix">
    <h2 class="h3">Results:</h2>
    <table class="table">
    <thead>
    <tr>
        <th>Session</th>
        <th>Date</th>
        <th>Start/End</th>
        <th>Location</th>
        <th>POC</th>
    </tr>
</thead>
<tbody>
{#each $events_slct.session_obj_li as session_obj}
<tr>
    <td>
        <a
            href="/events_pres_mgmt/session/{session_obj.event_session_id_random}"
            class="btn btn-md variant-ghost-secondary hover:variant-filled-secondary min-w-full max-w-md"
            >
            <span class="fas fa-eye mx-1"></span>
            <span class="grow overflow-x-scroll">
            <strong>{session_obj.name}</strong>
            </span>
        </a>
    </td>
    <td>
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'dddd')}
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'date_long_month_day')}
        </span>
    <td>
        {#if session_obj.start_datetime}
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.start_datetime,'time_short')}
        </span>
        &ndash;<wbr>
        <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj.end_datetime,'time_short')}
        </span>
        {:else}
        -- not set --
        {/if}
    </td>
    <td>{session_obj.event_location_name ?? '-- not set --'}</td>
    <td>
        {#if session_obj.poc_person_full_name}
            <span style="break-inside: avoid;">
                <span class="fas fa-user mx-1"></span>
                {session_obj.poc_person_full_name}
            </span>
            <!-- <br> -->
            {#if $ae_loc.trusted_access}
            <span style="break-inside: avoid;">
                <a href="mailto:{session_obj.poc_person_primary_email}" class="hover:underline">
                    <span class="fas fa-envelope mx-1"></span>
                    {session_obj.poc_person_primary_email}
                </a>
            </span>
            {/if}
        {:else}
            -- not set --
        {/if}

        {#if $ae_loc.trusted_access}

        {#if session_obj.event_session_id_random == $events_slct.event_session_id && ae_tmp[$events_slct.event_session_id] && ae_tmp[$events_slct.event_session_id].show__edit_poc_person}
        <Element_ae_crud
            trigger_patch={ae_triggers.update_person_poc}
            api_cfg={$ae_api}
            object_type={'event_session'}
            object_id={$events_slct?.event_session_id}
            field_name={'poc_person_id_random'}
            field_type={'button'}
            field_value={ae_tmp[$events_slct.event_session_id].poc_person_id}
            allow_null={false}
            hide_edit_btn={true}
            outline_element={false}
            show_crud={false}
            display_inline={true}
            class_li={'m-1'}
            on:ae_crud_updated={e => {
                console.log(`ae_crud_updated:`, e.detail);

                events_func.handle_load_ae_obj_id__event_session({api_cfg: $ae_api, event_session_id: $events_slct?.event_session_id, log_lvl: 1})
                .then(function (load_results) {
                    ae_tmp[$events_slct.event_session_id].poc_person_id = null;
                    ae_tmp[$events_slct.event_session_id].show__edit_poc_person = false;

                    $events_slct.event_session_id = null;
                    $events_slct.event_obj = null;

                    // Careful with the trigger_patch. It will keep firing if not reset.
                    ae_triggers.update_person_poc = false;

                    // Maybe reload page?
                    // window.location.reload();
                });
            }}
            >
            {#await $slct.person_obj_li}
                <span class="fas fa-spinner fa-spin mx-1"></span>
            {:then person_obj_li}
            {#if  person_obj_li && person_obj_li.length > 0}
                <label class="text-sm">PoC:
                <select
                    bind:value={ae_tmp[$events_slct.event_session_id].poc_person_id}
                    class="select min-w-fit max-w-md text-sm"
                    >
                <option value="">-- Select a person --</option>
                {#each person_obj_li as person_obj}
                    <option
                        value={person_obj.person_id_random}
                        selected={person_obj.person_id_random == $events_slct?.event_session_obj?.poc_person_id_random}
                        >
                        {person_obj.full_name}
                        ({person_obj.primary_email})
                        <!-- (ID: {person_obj.person_id_random}) -->
                    </option>
                {/each}
                </select>
                </label>

                <button
                    type="button"
                    disabled={ae_tmp[$events_slct.event_session_id].poc_person_id == $events_slct?.event_session_obj?.poc_person_id_random}
                    on:click={() => {
                        console.log('Save the POC person for the session.');

                        let person_id = ae_tmp[$events_slct.event_session_id].poc_person_id;
                        console.log('Selected person ID:', person_id);

                        ae_triggers.update_person_poc = true;
                    }}
                    class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
                    >
                    <span class="fas fa-save mx-1"></span>
                    Save
                </button>
            {/if}
            {/await}
        </Element_ae_crud>
        {/if}

        {#if ae_tmp[$events_slct.event_session_id] && ae_tmp[$events_slct.event_session_id].show__edit_poc_person}
        <button
            type="button"
            on:click={() => {
                console.log('Cancel the POC person for the session.');

                ae_tmp[$events_slct.event_session_id].poc_person_id = null;
                ae_tmp[$events_slct.event_session_id].show__edit_poc_person = false;

                $events_slct.event_session_id = null;
                $events_slct.event_obj = null;
            }}
            class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
            >
            <span class="fas fa-times mx-1"></span>
            Cancel
        </button>
        {:else}
        <button
            type="button"
            on:click={() => {
                console.log('Edit the POC person for the session.');

                let params = {
                    qry__limit: 300,
                }

                $slct.person_obj_li = core_func.handle_load_ae_obj_li__person({api_cfg: $ae_api, account_id: $slct.account_id, params: params});

                $events_slct.event_session_id = session_obj.event_session_id_random;

                ae_tmp[$events_slct.event_session_id] = {
                    poc_person_id: session_obj?.poc_person_id_random,
                    show__edit_poc_person: true,
                };
                // }
                // ae_tmp[$events_slct.event_session_id].poc_person_id = $events_slct?.event_session_obj?.poc_person_id_random;
                // ae_tmp[$events_slct.event_session_id].show__edit_poc_person = true;
            }}
            class="btn btn-sm variant-soft-warning hover:variant-ghost-warning"
            >
            <span class="fas fa-edit mx-1"></span>
            Edit
        </button>
        {/if}

        {/if} <!-- $ae_loc.trusted_access -->
    </td>
</tr>
{/each}
</tbody>
</table>
</section>
{:else}
<p class="text-center text-2xl bg-gray-100 p-4 rounded-md">
    No results to show. Please use the search above to find your session.
</p>
{/if}

</section>


<style lang="postcss">
/* Use the div.ae_quick_modal_container to block background clicks when using the section.ae_quick_popover. */
div.ae_quick_modal_container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 100;
    background-color: hsla(0, 0%, 0%, .5);
}

/* The section.ae_quick_popover should be above the rest of the content and centered on the page. */
section.ae_quick_popover {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    background-color: hsla(0, 0%, 100%, .95);
    padding: 1rem;
    border-radius: .5rem;
    box-shadow: 0 0 1rem hsla(0, 0%, 0%, .5);

    min-height: 30%;
    min-width: 80%;
}
</style>
