<script lang="ts">
interface Props {
    log_lvl?: number;
    lq__event_obj: any;

    event_presenter_obj_li?: any[];

    rpt__name?: string;
    rpt__sort?: string;
    rpt__order_by_li?: any;
    rpt__enabled?: string;
    rpt__hidden?: string;
    rpt__limit?: number;

    qry__status?: string;
    qry__count?: number;

    qry__trigger?: boolean;

    show_presentation_fields?: boolean;
    show_session_fields?: boolean;
    hide_session_code?: boolean;
}

let {
    log_lvl = $bindable(0),
    lq__event_obj, // This is the live query so it updates automatically anyways?

    event_presenter_obj_li = $bindable([]),

    rpt__name = $bindable('presenters_overview'), // presenters_agree, presenters_biography, presenters_overview
    rpt__sort = $bindable('updated_on'), // updated_on, given_name, family_name, email, start_datetime
    rpt__order_by_li = $bindable({
        updated_on: 'DESC',
        priority: 'DESC',
        sort: 'DESC',
        given_name: 'ASC',
        family_name: 'ASC',
        email: 'ASC',
        created_on: 'DESC'
    }),
    rpt__enabled = $bindable('all'), // enabled, disabled, all
    rpt__hidden = $bindable('all'), // hidden, not_hidden, all
    rpt__limit = $bindable(150),

    qry__status = $bindable(''), // loading, processing, done
    qry__count = $bindable(0),

    qry__trigger = $bindable(true),

    show_presentation_fields = false,
    show_session_fields = false,
    hide_session_code = false
}: Props = $props();

// *** Import Svelte specific

// *** Import other supporting libraries

// *** Import Aether specific variables and functions
import type { key_val } from '$lib/stores/ae_stores';
// import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_snip,
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
// import { db_events } from "$lib/ae_events/db_events";
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { pres_mgmt_loc } from '$lib/stores/ae_events_stores__pres_mgmt.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import Comp_event_presenter_obj_tbl from './../presenter/ae_comp__event_presenter_obj_tbl_wrapper.svelte';
import {
    ArrowUpDown,
    Check,
    IdCard,
    List,
    LoaderCircle,
    ToggleLeft,
    ToggleRight,
    X
} from '@lucide/svelte';
let ae_promises: key_val = $state({});

let sort_option_kv: key_val = {
    updated_on: {
        name: 'Updated On',
        field_kv: {
            event_presentation_start_datetime: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            given_name: 'ASC',
            family_name: 'ASC',
            email: 'ASC',
            updated_on: 'DESC',
            created_on: 'DESC'
        }
    },
    given_name: {
        name: 'Given Name',
        field_kv: {
            given_name: 'ASC',
            family_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            email: 'ASC',
            created_on: 'DESC'
        }
    },
    family_name: {
        name: 'Family Name',
        field_kv: {
            family_name: 'ASC',
            given_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            email: 'ASC',
            created_on: 'DESC'
        }
    },
    email: {
        name: 'Email',
        field_kv: {
            email: 'ASC',
            given_name: 'ASC',
            family_name: 'ASC',
            updated_on: 'DESC',
            priority: 'DESC',
            sort: 'DESC',
            created_on: 'DESC'
        }
    },
    start_datetime: {
        name: 'Start Date Time',
        field_kv: {
            event_presentation_start_datetime: 'ASC',
            priority: 'DESC',
            sort: 'DESC',
            given_name: 'ASC',
            family_name: 'ASC',
            email: 'ASC',
            updated_on: 'DESC',
            created_on: 'DESC'
        }
    }
};

$effect(() => {
    if (qry__trigger) {
        qry__trigger = false;
        if (rpt__name == 'presenters_agree') {
            handle_search__event_presenter({
                agree: pres_mgmt_loc.current.rpt__presenter_agree ?? false,
                ft_search_str: '',
                lk_search_str: '',
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else if (rpt__name == 'presenters_biography') {
            handle_search__event_presenter({
                biography: true,
                ft_search_str: '',
                lk_search_str: '',
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        } else if (rpt__name == 'presenters_overview') {
            // NOT READY YET: Show overview of presenters' statuses. (for LCI)
            handle_search__event_presenter({
                ft_search_str: '',
                lk_search_str: '',
                order_by_li: rpt__order_by_li,
                log_lvl: log_lvl
            });
        }
    }
});

async function handle_search__event_presenter({
    agree = null,
    biography = null,
    ft_search_str = '',
    lk_search_str = '',
    enabled = rpt__enabled,
    hidden = rpt__hidden,
    limit = rpt__limit,
    order_by_li = rpt__order_by_li,
    // params = {
    //     'qry__enabled': pres_mgmt_loc.current.qry_enabled ?? 'enabled',
    //     'qry__hidden': pres_mgmt_loc.current.qry_hidden ?? 'not_hidden',
    //     'qry__limit': pres_mgmt_loc.current.qry_limit__presenters ?? 199,
    // },
    // try_cache = true,
    log_lvl = 0
}: {
    agree?: null | boolean;
    biography?: null | boolean;
    ft_search_str?: string;
    lk_search_str?: string;
    // search_delay?: number, // In milliseconds
    // max_tries?: number,
    enabled?: 'enabled' | 'all' | 'not_enabled' | string;
    hidden?: 'hidden' | 'all' | 'not_hidden' | string;
    limit?: number;
    order_by_li?: any; // Order by fields and directions.
    // params?: key_val,
    // try_cache?: boolean,
    log_lvl?: number;
}) {
    if (log_lvl) {
        console.log('handle_search__event_presenter()');
    }

    $events_sess.pres_mgmt.status_qry__search = 'loading';
    $events_sess.pres_mgmt.status_rpt[rpt__name] = 'loading';
    qry__status = 'loading';
    qry__count = 0;

    $events_sess.event_presenter_obj_li = [];
    $events_slct.event_presenter_obj_li = []; // Clear out any previous results.
    event_presenter_obj_li = [];

    // let order_by_li = {'updated_on': 'DESC', 'priority': 'DESC', 'sort': 'DESC', 'given_name': 'ASC', 'family_name': 'ASC', 'email': 'ASC', 'created_on': 'DESC'};

    ae_promises.search__event_presenter = events_func
        .search__event_presenter({
            api_cfg: $ae_api,
            event_id: $events_slct.event_id,
            agree: agree,
            biography: biography,
            fulltext_search_qry_str: ft_search_str,
            ft_presenter_search_qry_str: null,
            like_search_qry_str: lk_search_str,
            like_presentation_search_qry_str: lk_search_str,
            like_presenter_search_qry_str: lk_search_str,
            // external_event_id: pres_mgmt_loc.current.default__external_registration_id,
            enabled: enabled as any,
            hidden: hidden as any,
            limit: limit,
            order_by_li: order_by_li,
            // try_cache: try_cache,
            log_lvl: log_lvl
        })
        .then(function (search_results) {
            // Processing the results from the search.
            if (!search_results) {
                search_results = [];
            }
            $events_sess.pres_mgmt.status_qry__search = 'processing';
            $events_sess.pres_mgmt.status_rpt[rpt__name] = 'processing';
            qry__status = 'processing';
            qry__count = search_results?.length ?? 0;

            $events_sess.event_presenter_obj_li = search_results;
            // $events_slct.event_presenter_obj_li = search_results;
            event_presenter_obj_li = search_results;
            if (log_lvl) {
                console.log(event_presenter_obj_li);
            }
            // $events_sess.pres_mgmt.status_qry__search = 'done';
        })
        .finally(() => {
            if (log_lvl) {
                console.log(
                    'TEST SEARCH - Search done. Pulling out the event_presenter_id_randoms.'
                );
            }
            // console.log(`TEST search: ${$lq_kv__event_presenter_obj_li}`);

            // event_presenter_id_random_li = [];

            // We need to loop through the array of objects and get the event_presenter_id_random from each object a new list of event_presenter_id_randoms. Then we can use this list to get the full objects from the database.
            // let tmp_li = []; // This is to prevent the array from constantly updating and triggering the liveQuery.
            // for (let i = 0; i < $events_slct.event_presenter_obj_li.length; i++) {
            //     tmp_li.push($events_slct.event_presenter_obj_li[i].event_presenter_id);
            // }
            // event_presenter_id_random_li = tmp_li;

            // event_presenter_id_random_li = $events_slct.event_presenter_obj_li.map(presenter_obj => presenter_obj.event_presenter_id);

            // Finally done with the search.
            $events_sess.pres_mgmt.status_qry__search = 'done';
            $events_sess.pres_mgmt.status_rpt[rpt__name] = 'done';

            qry__status = 'done';

            // if (log_lvl > 1) {
            //     console.log(`TEST SEARCH - event_presenter_id_random_li:`, event_presenter_id_random_li);
            //     // console.log(`TEST SEARCH - search live query: ${$lq_kv__event_presenter_obj_li}`);
            // }
        });
}
</script>

<!-- Show presenters that have agreed -->
{#if rpt__name == 'presenters_agree'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else if pres_mgmt_loc.current.rpt__presenter_agree}
                <Check size="1em" class="m-1" />
            {:else}
                <X size="1em" class="m-1" />
            {/if}
            Presenters
            {#if pres_mgmt_loc.current.rpt__presenter_agree}Agreed{:else}Not
                Agreed{/if}
            <!-- {event_presenter_obj_li.length ?? 0} -->
        </h3>

        <div class="flex flex-row items-center justify-center">
            <button
                type="button"
                onclick={() => {
                    pres_mgmt_loc.current.rpt__presenter_agree =
                        !pres_mgmt_loc.current.rpt__presenter_agree;

                    qry__trigger = true;
                    rpt__name = 'presenters_agree';
                }}
                class="ae_btn_info btn btn-sm m-1">
                {#if pres_mgmt_loc.current.rpt__presenter_agree}
                    <!-- <span class="fas fa-check m-1"></span> -->
                    <ToggleRight size="1em" class="m-1" />
                    Agreed
                {:else}
                    <!-- <span class="fas fa-times m-1"></span> -->
                    <ToggleLeft size="1em" class="m-1" />
                    Not Agreed
                {/if}
            </button>
        </div>
    </header>
{/if}

<!-- Show presenters with bios -->
{#if pres_mgmt_loc.current.show_report == 'presenters_biography'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else}
                <IdCard size="1em" class="m-1" />
            {/if}
            Presenters with Bios
        </h3>
    </header>
{/if}

<!-- Show overview of presenters (status checklist) -->
{#if pres_mgmt_loc.current.show_report == 'presenters_overview'}
    <header
        class="flex w-full flex-row flex-wrap items-center justify-center gap-1">
        <h3 class="h4 text-center">
            {#if qry__status == 'loading'}
                <LoaderCircle size="1em" class="m-1 animate-spin" />
                <!-- <span>Loading...</span> -->
            {:else}
                <List size="1em" class="m-1" />
            {/if}
            Presenters Overview
        </h3>

        <div class="flex flex-row items-center justify-center">
            <!-- Sorting options (presenter name, start_datetime, updated_on) -->
            <label class="label text-sm">
                <ArrowUpDown size="1em" class="m-1" />
                Sort by:

                <select
                    class="select ae_btn_info m-1 inline-block w-36 px-1 text-sm"
                    bind:value={rpt__sort}
                    onchange={(event) => {
                        if ((event.target as HTMLInputElement).value) {
                            rpt__sort = (event.target as HTMLInputElement)
                                .value;
                        } else {
                            rpt__sort = 'updated_on';
                        }

                        rpt__order_by_li =
                            sort_option_kv[rpt__sort]?.field_kv ??
                            sort_option_kv['updated_on'].field_kv;

                        // ae_promises.handle_search__event_presenter = handle_search__event_presenter({
                        //     // ft_search_str: '',
                        //     // lk_search_str: '',
                        //     order_by_li: pres_mgmt_loc.current.qry__presenter_order_by_li,
                        //     log_lvl: log_lvl,
                        // });
                        qry__trigger = true;
                        rpt__name = 'presenters_overview';
                    }}>
                    <option value="updated_on">Updated On</option>
                    <option value="given_name">Given Name</option>
                    <option value="family_name">Family Name</option>
                    <option value="email">Email</option>
                    <option value="start_datetime">Start Date Time</option>
                    <!-- <option value="created_on">Created On</option> -->
                    <!-- <option value="sort">Sort</option> -->
                    <!-- <option value="priority">Priority</option> -->
                </select>
            </label>
        </div>
    </header>
{/if}

{#if event_presenter_obj_li}
    <Comp_event_presenter_obj_tbl
        bind:event_presenter_obj_li
        show_presentation_fields={true}
        show_session_fields={true}
        {hide_session_code}
        {log_lvl}></Comp_event_presenter_obj_tbl>
{/if}
