<script lang="ts">
// Imports
import type { key_val } from '$lib/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import Element_ae_crud from '$lib/element_ae_crud.svelte';
// import Element_data_store from '$lib/element_data_store_v2.svelte';
import Comp_event_presenter_obj_li from '../events/[event_id]/presenter/ae_comp__event_presenter_obj_li_wrapper.svelte';
import Element_manage_event_file_li from '$lib/element_manage_event_file_li_direct.svelte';

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

// Exports
export let log_lvl: number = 0;
export let container_class_li: string|Array<string> = [];
// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'

export let link_to_type: null|string;
export let link_to_id: null|string;
export let lq__event_session_obj_li: any;

export let hide__session_location: boolean = false;
export let hide__session_poc: boolean = false;
export let show__launcher_link: boolean = false;
export let show__launcher_link_legacy: boolean = false;
export let show__location_link: boolean = false;
export let show__session_files: boolean = false;
export let show__session_presentations: boolean = false;
// export let allow_basic: boolean = false;
// export let allow_moderator: boolean = false;

if (log_lvl) {
    console.log(`link_to_type: ${link_to_type}; link_to_id: ${link_to_id}`);
}

// Variables
// let ae_promises: key_val = {};
let ae_tmp: key_val = {};
let ae_triggers: key_val = {};

// Functions and Logic
</script>

<!-- xs:max-w-sm lg:max-w-100 -->
<!-- sm:border-red-200 md:border-yellow-200 lg:border-gray-100 -->
<section
    class="
    ae_comp event_session_obj_li
    border border-2 border-dashed border-x-red-500 border-y-white
    sm:border-x-red-400 md:border-x-yellow-400 lg:border-x-gray-100
    px-0.5 py-2 space-y-2
    min-w-full
    w-full
    container overflow-x-scroll {container_class_li}
    "
    >


{#if $lq__event_session_obj_li?.length}
<!-- {#if $events_slct.event_session_obj_li?.length == event_session_id_random_li?.length && event_session_id_random_li.length == $lq__event_session_obj_li?.length} -->
<!-- {#if $events_slct?.event_session_obj_li && $events_slct.event_session_obj_li.length > 0} -->

<!-- <section class="ae_h_scrollfix py-2 space-y-2"> -->
<!-- <section class="py-2 space-y-2 xs:max-w-sm lg:max-w-100 container overflow-x-scroll"> -->

    <h2 class="h3">
        <span class="text-md">
        Sessions:
        </span>

        {#if $lq__event_session_obj_li?.length}
        <span class="text-3xl font-bold bg-success-100 px-4 border rounded-lg border-success-200"
                title="Count {$lq__event_session_obj_li?.length ?? 'None'}"
                >
            <span class="fas fa-list-ol mx-4"></span>
            {$lq__event_session_obj_li?.length ?? 'None'}
        </span>
        {/if}
    </h2>

<table class="table table-auto table-striped table-hover">
<thead>
    <tr>
        <th>Session</th>
        <th>Date</th>
        <th>
            <span class="md:hidden">
            Times
            </span>
            <span class="hidden md:inline">
            Start&ndash;End
            </span>
        </th>
        <th
            class:hidden={hide__session_location}
            >Location</th>
        <th
            class:hidden={hide__session_poc}
            >POC</th>
    </tr>
</thead>
<tbody>
<!-- {#each $events_slct?.event_session_obj_li as session_obj} -->
{#each $lq__event_session_obj_li as session_obj}
<tr
    class:dim={session_obj?.hide}
    >
    <td>
        <a
            href="/events/{session_obj?.event_id}/session/{session_obj?.event_session_id}"
            class="
                btn btn-md
                variant-ghost-secondary hover:variant-filled-secondary
                min-w-full max-w-md
                sm:w-80
                text-xs md:text-sm lg:text-base
                md:max-w-xs md:p-1
                sm:btn-sm
                md:btn-md
                "
            title="{session_obj?.name} - {session_obj?.event_session_id_random}"
            >
            <span class="fas fa-eye m-0.25"></span>
            <!-- overflow-x-scroll -->
            <span class="grow overflow-hidden text-wrap text-left max-h-8 sm:max-h-10 md:max-h-10 lg:max-h-12">
            <!-- <div> -->
            <strong>{session_obj?.name}</strong>
            <!-- </div> -->
            </span>
            {#if session_obj?.file_count_all}
                <span class="badge variant-glass-success hover:variant-filled-success" title="{session_obj?.file_count_all}&times; files under session">
                    <span class="fas fa-file-alt mx-1"></span>
                    {session_obj?.file_count_all}&times;
                </span>
            {:else}
                <!-- Nothing -->
            {/if}
        </a>

        {#if show__session_presentations && $ae_loc.manager_access}
        <Comp_event_presenter_obj_li
            link_to_type={'event_session'}
            link_to_id={session_obj?.event_session_id_random}
            display_mode={'minimal'}
            log_lvl={log_lvl}
            >
        </Comp_event_presenter_obj_li>
        {/if}


        {#if show__session_files && $ae_loc.manager_access}
        <Element_manage_event_file_li
            link_to_type={'event_session'}
            link_to_id={session_obj?.event_session_id_random}
            allow_basic={$events_loc.auth__kv.session[$events_slct.event_session_id] || $events_loc.auth__kv.presenter[$events_slct.event_presenter_id]}
            allow_moderator={$events_loc.auth__kv.session[$events_slct.event_session_id]}
            container_class_li={''}
            display_mode={'minimal'}
            />
        {/if}

    </td>
    <td>
        <span class="flex flex-col text-xs lg:text-sm">
            <span>
            {ae_util.iso_datetime_formatter(session_obj?.start_datetime,'dddd')}
            </span>
            <span style="break-inside: avoid;">
            {ae_util.iso_datetime_formatter(session_obj?.start_datetime,'date_long_month_day')}
            </span>
        </span>
    <td>
        <span class="flex flex-col items-center md:flex-row md:items-start md:text-center max-w-36 text-xs lg:text-sm">
            {#if session_obj?.start_datetime}
            <span style="break-inside: avoid;">
                {ae_util.iso_datetime_formatter(session_obj?.start_datetime,'time_12_short')}
            </span>
            <span class="grow">
            &ndash;
            </span>
            <span style="break-inside: avoid;">
                {ae_util.iso_datetime_formatter(session_obj?.end_datetime,'time_12_short')}
            </span>
            {:else}
            {@html ae_snip.html__not_set}
            {/if}
        </span>
    </td>

    <td
        class:hidden={hide__session_location}
        >
        <!-- Minimum level access to see the link here is "trusted". -->
        <!-- BEGIN: Legacy link -->
        {#if show__launcher_link_legacy}
            <a
                data-sveltekit-preload-data="false"
                href="/event/{session_obj?.event_id_random}/launcher/{session_obj?.event_location_id_random}"
                class="btn btn-sm variant-glass-secondary hover:variant-filled-secondary text-xs lg:text-sm"
                title="Launcher: {session_obj?.event_location_name} {session_obj?.event_location_id_random}"
                >
                <span class="fas fa-paper-plane m-1"></span>
                {@html session_obj?.event_location_name ? session_obj?.event_location_name : ae_snip.html__not_set}
            </a>
        {:else}
            <span>
                {session_obj?.event_location_name ?? '-- not set --'}
            </span>
        {/if}
        <!-- END: Legacy Link -->

        {#if show__launcher_link}
            <a
                href="/events/{session_obj?.event_id_random}/launcher/{session_obj?.event_location_id_random}?session_id={session_obj?.event_session_id_random}"
                class="btn btn-sm variant-glass-surface hover:variant-filled-secondary text-xs lg:text-sm"
                title="Launcher: {session_obj?.event_location_name} {session_obj?.event_location_id_random}"
                >
                <span class="fas fa-plane m-1"></span>
                {@html session_obj?.event_location_name ? session_obj?.event_location_name : ae_snip.html__not_set}
            </a>
        {:else}
            <!-- <span>
                {session_obj?.event_location_name ?? '-- not set --'}
            </span> -->
        {/if}
        {#if show__location_link}
            <a
                href="/events/{session_obj?.event_id_random}/location/{session_obj?.event_location_id_random}"
                class="btn btn-sm variant-glass-surface hover:variant-filled-tertiary text-xs lg:text-sm"
                title="Location: {session_obj?.event_location_name} {session_obj?.event_location_id_random}"
                >
                <span class="fas fa-map-marker-alt m-1"></span>
                <!-- {@html session_obj?.event_location_name ? session_obj?.event_location_name : ae_snip.html__not_set} -->
            </a>
        {/if}
    </td>

    <td
        class:hidden={hide__session_poc}
        >
        <span class="flex flex-col items-start lg:flex-row lg:items-center lg:justify-between text-xs lg:text-sm">
        {#if session_obj?.poc_person_full_name}
            <span style="break-inside: avoid;" class="">
                <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;" class="text-xs">
                <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}
        {@html ae_snip.html__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.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"
            class:hidden={!$ae_loc.edit_mode}
            >
            <span class="fas fa-edit mx-1"></span>
            Edit
        </button>
        {/if}

        {/if} <!-- $ae_loc.trusted_access -->

        </span> <!-- flex flex-col items-center md:flex-row md:items-start -->
    </td>
</tr>
{/each}
</tbody>
</table>
<!-- </section> -->

{:else}
    <p class="text-center text-2xl bg-gray-100 p-4 rounded-md">
        <span class="fas fa-exclamation-triangle text-2xl text-yellow-500"></span>
        No results to show. Please use the search above to find your session.
        <span class="fas fa-exclamation-triangle text-2xl text-yellow-500"></span>
    </p>
    <!-- <div class="text-sm text-gray-500 text-center"> -->
    <!-- Query results length: {$events_slct.event_session_obj_li?.length}; -->
    <!-- ID list length: {event_session_id_random_li?.length}; -->
    <!-- LQ results length: {$lq__event_session_obj_li?.length} -->
    <!-- LQ KV results length: {$lq_kv__event_session_obj_li?.length} -->
    <!-- </div> -->
{/if}

</section>