<script lang="ts">
interface Props {
    // Exports
    container_class_li?: string | Array<string>;
    // export let event_presenter_id_random_li: Array<string>;
    lq__event_presenter_obj_li: any;
    // export let allow_moderator: boolean = false;
    show_presentation_fields?: boolean;
    show_session_fields?: boolean;
    hide_session_code?: boolean;
    log_lvl?: number;
}

let {
    container_class_li = [],
    lq__event_presenter_obj_li,
    show_presentation_fields = false,
    show_session_fields = false,
    hide_session_code = false,
    log_lvl = $bindable(0)
}: Props = $props();

// Imports
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 {
    FileSpreadsheet,
    ListOrdered,
    Mail,
    Presentation,
    ToggleLeft,
    ToggleRight,
    User
} from '@lucide/svelte';
// export let display_mode: string = 'default'; // 'default', 'compact', 'minimal', 'launcher'
// export let link_to_type: string;
// export let link_to_id: string;

// export let allow_basic: boolean = false;

$effect(() => {
    if (log_lvl) {
        console.log(
            `container_class_li: ${container_class_li}; show_presentation_fields: ${show_presentation_fields}; show_session_fields: ${show_session_fields}`
        );
        // 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
// let lq__event_presenter_obj = liveQuery(
//     () => db_events.presenter.get($events_slct.event_presenter_id)
// );

// let lq_kv__event_presenter_obj_li = liveQuery(
//     () => db_events.presenter
//     .bulkGet(event_presenter_id_random_li)
// );

function generate_presenter_export_csv(ae_obj_li: any[]) {
    console.log(`*** generate_presenter_export_csv() ***`, ae_obj_li);

    // We need to create a list with the column names and then a list of lists with the data.
    let csv_data: any[][] = [];
    let csv_columns = [
        'Presenter ID',
        'Name',
        'Email',
        'Agree',
        'Files',
        'Code',
        'Session',
        'Start datetime',
        'Presentation',
        'Presentation time',
        'Updated On'
    ];
    csv_data.push(csv_columns);

    for (let i = 0; i < ae_obj_li.length; i++) {
        let csv_row: any[] = [];
        csv_row.push(ae_obj_li[i].event_presenter_id);
        csv_row.push(ae_obj_li[i].full_name ?? ae_obj_li[i].given_name);
        csv_row.push(ae_obj_li[i].email ?? '');
        csv_row.push(ae_obj_li[i].agree ? 'Yes' : 'No');
        csv_row.push(ae_obj_li[i].file_count ?? '0');
        csv_row.push(ae_obj_li[i].event_session_code ?? '');
        csv_row.push(ae_obj_li[i].event_session_name ?? '');
        csv_row.push(
            ae_obj_li[i].event_session_start_datetime
                ? ae_util.iso_datetime_formatter(
                      ae_obj_li[i].event_session_start_datetime,
                      'datetime_iso_12_no_seconds'
                  )
                : ''
        );
        csv_row.push(ae_obj_li[i].event_presentation_name ?? '');
        csv_row.push(
            ae_obj_li[i].event_presentation_start_datetime
                ? ae_util.iso_datetime_formatter(
                      ae_obj_li[i].event_presentation_start_datetime,
                      'time_12_short'
                  )
                : ''
        );
        csv_row.push(
            ae_obj_li[i].updated_on
                ? ae_util.iso_datetime_formatter(
                      ae_obj_li[i].updated_on,
                      'datetime_iso_12_no_seconds'
                  )
                : ''
        );

        csv_data.push(csv_row);
    }

    console.log('CSV Data:', csv_data);

    let csv_content_str = '';
    csv_data.forEach(function (row) {
        csv_content_str += row.join(';');
        csv_content_str += '\n';
    });

    const blob = new Blob([csv_content_str], {
        type: 'text/csv;charset=utf-8;'
    });
    const obj_url = URL.createObjectURL(blob);

    const download_link = document.createElement('a');
    download_link.setAttribute('href', obj_url);
    download_link.setAttribute(
        'download',
        `presenter_list_${ae_util.iso_datetime_formatter()}.csv`
    );
    download_link.setAttribute('style', 'display: none;');
    download_link.textContent = 'Download CSV';

    // document.querySelector('body').appendChild(download_link);
    const container = document.getElementById('download_csv_container');
    if (container) {
        container.appendChild(download_link);
    } else {
        document.body.appendChild(download_link);
    }

    // Automatically download the file
    download_link.click();

    return csv_data;
}

let horiz_scroll_warning: boolean = $state(false);
let horiz_check_element: HTMLElement | null = $state(null);

// Check if element is scrolling horizontally
$effect(() => {
    if (
        horiz_check_element &&
        horiz_check_element.scrollWidth > horiz_check_element.offsetWidth
    ) {
        horiz_scroll_warning = true;
        // console.log('Element is too wide for the container. Horizontal scrolling detected.');
    } else {
        horiz_scroll_warning = false;
        // console.log('Element fits within the container. No horizontal scrolling.', horiz_check_element);
    }
});
</script>

<section
    class:border-r-2={horiz_scroll_warning}
    class:border-dashed={horiz_scroll_warning}
    class:border-warning-900-100={horiz_scroll_warning}
    class="ae_comp event_presenter_obj_tbl {container_class_li}  container max-w-screen overflow-auto">
    {#if $lq__event_presenter_obj_li && $lq__event_presenter_obj_li?.length}
        <div
            bind:this={horiz_check_element}
            id="tbl_container"
            class="space-y-2 pb-8">
            <header
                class="flex flex-row flex-wrap items-center justify-between gap-1">
                <h2 class="h3">
                    <span class="text-base"> Results: </span>

                    {#if $lq__event_presenter_obj_li.length}
                        <span
                            class="preset-filled-success-100-900 rounded-lg px-4 text-3xl font-bold"
                            title="Count {$lq__event_presenter_obj_li.length ??
                                'None'}">
                            <ListOrdered size="1em" class="mx-4" />
                            {$lq__event_presenter_obj_li.length ??
                                'None'}&times;
                        </span>
                    {/if}
                </h2>

                <div
                    class="flex flex-row flex-wrap items-center justify-end gap-1"
                    class:hidden={!$ae_loc.edit_mode}>
                    <button
                        type="button"
                        class="btn btn-sm preset-tonal-warning border-warning-500 generate_csv_btn mb-1 border"
                        onclick={() => {
                            if (
                                !confirm(
                                    'Generate and download a CSV file with the presenter list?'
                                )
                            ) {
                                return false;
                            }

                            let csv_data = generate_presenter_export_csv(
                                $lq__event_presenter_obj_li
                            );
                            console.log('CSV Data:', csv_data);
                        }}>
                        <FileSpreadsheet size="1em" class="mx-1" />
                        Export Presenters CSV
                    </button>
                    <span id="download_csv_container"></span>

                    {#if show_session_fields}
                        <button
                            type="button"
                            onclick={() => {
                                show_session_fields = !show_session_fields;
                            }}
                            class="btn btn-sm {show_session_fields
                                ? 'ae_btn_surface'
                                : 'ae_btn_surface_outlined'}"
                            title="Show or hide the session-related column fields.">
                            <ToggleRight size="1em" class="m-1" />
                            Showing Session Fields
                        </button>
                    {:else}
                        <button
                            type="button"
                            onclick={() => {
                                show_session_fields = !show_session_fields;
                            }}
                            class="btn btn-sm {show_session_fields
                                ? 'ae_btn_surface'
                                : 'ae_btn_surface_outlined'}"
                            title="Show or hide the session-related column fields.">
                            <ToggleLeft size="1em" class="m-1" />
                            Show Session Fields
                        </button>
                    {/if}

                    <!-- Show or hide the session code -->
                    {#if !hide_session_code}
                        <button
                            type="button"
                            onclick={() => {
                                hide_session_code = true;
                            }}
                            class="btn btn-sm ae_btn_surface"
                            title="Hide the session code column from view. Currently showing the Session Code column.">
                            <ToggleRight size="1em" class="m-1" />
                            Showing Session Code
                        </button>
                    {:else}
                        <button
                            type="button"
                            onclick={() => {
                                hide_session_code = false;
                            }}
                            class="btn btn-sm ae_btn_surface_outlined"
                            title="Show the session code column. Currently hiding the Session Code column from view.">
                            <ToggleLeft size="1em" class="m-1" />
                            Show Session Code
                        </button>
                    {/if}

                    {#if show_presentation_fields}
                        <button
                            type="button"
                            onclick={() => {
                                show_presentation_fields =
                                    !show_presentation_fields;
                            }}
                            class="btn btn-sm {show_presentation_fields
                                ? 'ae_btn_surface'
                                : 'ae_btn_surface_outlined'}"
                            title="Show or hide the extra presentation-related column fields.">
                            <ToggleRight size="1em" class="m-1" />
                            Showing Presentation Fields
                        </button>
                    {:else}
                        <button
                            type="button"
                            onclick={() => {
                                show_presentation_fields =
                                    !show_presentation_fields;
                            }}
                            class="btn btn-sm {show_presentation_fields
                                ? 'ae_btn_surface'
                                : 'ae_btn_surface_outlined'}"
                            title="Show or hide the extra presentation-related column fields.">
                            <ToggleLeft size="1em" class="m-1" />
                            Show Presentation Fields
                        </button>
                    {/if}
                </div>
            </header>

            <table
                class="table-striped table w-full table-auto text-xs lg:text-sm">
                <thead>
                    <tr>
                        <th class="px-4 py-2">Name</th>
                        <th class="px-4 py-2">Email</th>
                        <th class="px-4 py-2">Agree</th>
                        <th class="px-4 py-2">Files</th>

                        {#if show_session_fields}
                            <th
                                class="px-4 py-2"
                                class:hidden={hide_session_code}>
                                Code
                            </th>
                            <th class="px-4 py-2"> Session </th>
                            <th class="px-4 py-2">Start datetime</th>
                        {/if}

                        {#if show_presentation_fields}
                            <th class="px-4 py-2">Presentation</th>
                            <th class="px-4 py-2">Presentation time</th>
                        {/if}
                        <th class="px-4 py-2"> Updated On </th>
                    </tr>
                </thead>
                <tbody class="">
                    {#each $lq__event_presenter_obj_li as event_presenter_obj (event_presenter_obj.event_presenter_id)}
                        <tr class:dim={event_presenter_obj?.hide}>
                            <td class="px-4 py-2">
                                <User size="1em" />
                                <a
                                    href="/events/{event_presenter_obj?.event_id}/presenter/{event_presenter_obj?.event_presenter_id}"
                                    class="text-blue-500 underline hover:text-blue-800">
                                    {event_presenter_obj?.full_name ??
                                        '-- not set --'}
                                </a>
                            </td>
                            <td class="px-4 py-2">
                                <Mail size="1em" />
                                {#if event_presenter_obj?.email}
                                    <a
                                        href="mailto:{event_presenter_obj?.email}"
                                        class="text-blue-500 underline hover:text-blue-800">
                                        {event_presenter_obj?.email}
                                    </a>
                                {:else}
                                    <span class="dim">-- not set --</span>
                                {/if}
                            </td>
                            <td class="px-4 py-2"
                                >{event_presenter_obj?.agree
                                    ? 'Yes'
                                    : 'No'}</td>
                            <td class="px-4 py-2"
                                >{event_presenter_obj?.file_count ?? '0'}</td>

                            {#if show_session_fields}
                                <td
                                    class="px-4 py-2 lg:text-xs"
                                    class:hidden={hide_session_code}>
                                    {event_presenter_obj?.event_session_code ??
                                        '-- not set --'}
                                </td>
                                <td class="px-4 py-2 lg:text-xs">
                                    <Presentation size="1em" />
                                    <a
                                        href="/events/{event_presenter_obj?.event_id}/session/{event_presenter_obj?.event_session_id}"
                                        class="text-blue-500 underline hover:text-blue-800">
                                        {#if event_presenter_obj?.event_session_name}
                                            {event_presenter_obj?.event_session_name}
                                        {:else}
                                            <span class="dim"
                                                >-- not set --</span>
                                        {/if}
                                    </a>
                                </td>
                                <td class="px-4 py-2 text-sm">
                                    {#if event_presenter_obj?.event_session_start_datetime}
                                        {ae_util.iso_datetime_formatter(
                                            event_presenter_obj?.event_session_start_datetime,
                                            'datetime_iso_12_no_seconds'
                                        )}
                                    {:else}
                                        <span class="dim">-- not set --</span>
                                    {/if}
                                </td>
                            {/if}

                            {#if show_presentation_fields}
                                <td class="px-4 py-2 lg:text-xs"
                                    >{event_presenter_obj?.event_presentation_name}</td>
                                <td class="px-4 py-2 lg:text-xs">
                                    {#if event_presenter_obj?.event_presentation_start_datetime}
                                        {ae_util.iso_datetime_formatter(
                                            event_presenter_obj?.event_presentation_start_datetime,
                                            'time_12_short'
                                        )}
                                    {:else}
                                        <span class="dim">-- not set --</span>
                                    {/if}
                                </td>
                            {/if}

                            <td class="px-4 py-2 text-sm">
                                {#if event_presenter_obj?.updated_on}
                                    {ae_util.iso_datetime_formatter(
                                        event_presenter_obj?.updated_on,
                                        'datetime_iso_12_no_seconds'
                                    )}
                                {:else}
                                    <span class="dim">-- not set --</span>
                                {/if}
                            </td>
                        </tr>
                    {/each}
                </tbody>
            </table>
        </div>
    {:else}
        <p class="text-sm">No presenters available to show.</p>
    {/if}
</section>

<style>
.dim {
    opacity: 0.5;
    color: #999;
}
</style>
