<script lang="ts">
interface Props {
    // export let event_presenter_id: string;
    lq__event_presenter_obj: any;
    // export let lq__event_session_obj: any;
    log_lvl?: number;
}

let { lq__event_presenter_obj, log_lvl = 0 }: Props = $props();

console.log(`ae_events_pres_mgmt session [slug] form_agree.svelte`);

// Imports (external and then internal)
// import { onMount } from 'svelte';
// import { liveQuery } from "dexie";

import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import { api } from '$lib/ae_api/api';
import Element_data_store from '$lib/elements/element_data_store.svelte';

import {
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
// import { db_events } from "$lib/db_events";
import {
    events_sess,
    events_slct,
    events_trigger
} from '$lib/stores/ae_events_stores';
import { events_auth_loc } from '$lib/stores/ae_events_stores__auth.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';
import {
    Check,
    CircleCheck,
    LoaderCircle,
    TriangleAlert,
    X
} from '@lucide/svelte';
let ae_promises: key_val = $state({});
// let ae_tmp: key_val = {};
// let ae_triggers: key_val = {};

$events_sess.pres_mgmt.disable_submit__opt_out = false;

let tmp_agree = false;
let tmp_opt_out: key_val = {
    audio: false,
    video: false,
    transcription_and_publication: false,
    publication_in_app: false
};

// *** Functions and Logic
function prevent_default<T extends Event>(fn: (event: T) => void) {
    return function (event: T) {
        event.preventDefault();
        fn(event);
    };
}

async function handle_submit_form(event: SubmitEvent) {
    console.log('*** handle_submit_form() ***');

    $events_sess.pres_mgmt.disable_submit__opt_out = true;
    $events_sess.pres_mgmt.submit_status = 'saving';

    // Data in
    let form_data = new FormData(event.target as HTMLFormElement);
    console.log(form_data);

    let opt_out_di: key_val = ae_util.extract_prefixed_form_data({
        prefix: null,
        form_data: form_data,
        trim_values: true,
        bool_tf_str: true,
        log_lvl: 0
    });
    console.log(`opt_out_di:`, opt_out_di);

    // Data out
    let opt_out_do: key_val = {};
    opt_out_do.optout_audio = opt_out_di.optout_audio ?? false;
    opt_out_do.optout_video = opt_out_di.optout_video ?? false;
    opt_out_do.optout_transcription_and_publication =
        opt_out_di.optout_transcription_and_publication ?? false;
    opt_out_do.optout_publication_in_app =
        opt_out_di.optout_publication_in_app ?? false;

    opt_out_do.optout_updated_on = new Date().toISOString();

    console.log(`opt_out_do:`, opt_out_do);

    let data_out = {
        data_json: {
            ...$lq__event_presenter_obj.data_json,
            ...opt_out_do
        }
    };

    ae_promises.update__event_presenter_obj =
        await handle_update__event_presenter({
            obj_type: 'event_presenter',
            obj_id: $lq__event_presenter_obj?.event_presenter_id,
            data: data_out
        });
    console.log(ae_promises.update__event_presenter_obj);

    $events_sess.pres_mgmt.disable_submit__opt_out = false;
    $events_sess.pres_mgmt.submit_status = 'saved';
}

async function handle_update__event_presenter({
    obj_type,
    obj_id,
    data
}: {
    obj_type: string;
    obj_id: string;
    data: any;
}) {
    console.log('*** handle_update__event_presenter() ***');

    ae_promises.update__event_presenter_obj = api
        .update_ae_obj({
            api_cfg: $ae_api,
            obj_type: obj_type,
            obj_id: obj_id,
            fields: data,
            log_lvl: log_lvl
        })
        .then(async function (update__obj_result) {
            if (!update__obj_result) {
                console.log('The result was null or false.');
                return false;
            } else {
                console.log(`update__obj_result = `, update__obj_result);
            }
            $slct_trigger = 'load__event_presenter_obj_li';
            return update__obj_result;
        })
        .catch(function (error: any) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        });

    return ae_promises.update__event_presenter_obj;
}
</script>

{#if $lq__event_presenter_obj}
    {#if !$lq__event_presenter_obj?.agree}
        <div class="text-center text-error-700-300">
            <div class="">
                <X size="1.3em" class="m-1 text-error-700-300" />
                Not Yet Agreed
            </div>
            <div class="rounded-md border border-error-300-700
                preset-tonal-error p-4">
                Waiting for agreement to the Guest Speaker Consent and Release
                and Terms and Conditions before you can move on. Please review
                and mark as agreed below.
            </div>
        </div>
    {/if}

    <div
        class="border-surface-200-800 prose dark:prose-invert max-w-none space-y-4 rounded-lg border bg-surface-50-950 text-surface-900-100 p-4">
        <Element_data_store
            ds_code="event_presenter_agree_text"
            ds_type="html"
            class_li="p-2" />
    </div>

    <section
        class="space-y-2 rounded-lg border-2 text-lg p-2"
        class:border-warning-300-700={!$lq__event_presenter_obj?.agree}
        class:preset-filled-surface-400-600={!$lq__event_presenter_obj?.agree}
        class:border-success-300-700={$lq__event_presenter_obj?.agree}
        class:preset-tonal-success={$lq__event_presenter_obj?.agree}>
        <!-- Highlight the persons name, email, and that whole line. -->
        <p class="rounded-md p-2 text-lg"
           class:preset-tonal-warning={!$lq__event_presenter_obj?.agree}
           class:preset-tonal-success={$lq__event_presenter_obj?.agree}>
            {#if $lq__event_presenter_obj?.agree}
                <Check size="1em" class="mr-1 inline text-success-700" />
            {/if}
            <strong
                >{$lq__event_presenter_obj.full_name} ({$lq__event_presenter_obj.email})</strong>
            agrees to the following terms and conditions for the presentation:
        </p>
        <h3 class="h4 text-center">
            <span class="text-base">Presentation:</span>
            "{$lq__event_presenter_obj?.event_presentation_name}"
        </h3>

        <div class="w-full">
            <h3 class="h4 text-center">Opt-Out?</h3>
            <form
                class="modal-form {$ae_loc.hub.classes__form}"
                onsubmit={prevent_default(handle_submit_form)}>
                <p>
                    Speaker does not permit the use of presentation materials as
                    described in section(s), above for: (please check for all
                    that apply)
                </p>

                <label
                    class="label hover:preset-tonal-warning border-warning-500 rounded-md border p-1"
                    for="optout_audio">
                    <input
                        type="checkbox"
                        class="checkbox preset-tonal-warning border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500 border"
                        id="optout_audio"
                        name="optout_audio"
                        checked={$lq__event_presenter_obj.data_json
                            ?.optout_audio}
                        value={true} />
                    Opt-out - Audio Reproduction of Presentation
                </label>

                <label
                    class="label hover:preset-tonal-warning border-warning-500 rounded-md border p-1"
                    for="optout_video">
                    <input
                        type="checkbox"
                        class="checkbox preset-tonal-warning border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500 border"
                        id="optout_video"
                        name="optout_video"
                        checked={$lq__event_presenter_obj.data_json
                            ?.optout_video}
                        value={true} />
                    Opt-out - Video Reproduction of Presentation
                </label>

                <label
                    class="label hover:preset-tonal-warning border-warning-500 rounded-md border p-1"
                    for="optout_transcription_and_publication">
                    <input
                        type="checkbox"
                        class="checkbox preset-tonal-warning border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500 border"
                        id="optout_transcription_and_publication"
                        name="optout_transcription_and_publication"
                        checked={$lq__event_presenter_obj.data_json
                            ?.optout_transcription_and_publication}
                        value={true} />
                    Opt-out - Transcription and Publication of Presentation on LCI
                    Website
                </label>

                <label
                    class="label hover:preset-tonal-warning border-warning-500 rounded-md border p-1"
                    for="optout_publication_in_app">
                    <input
                        type="checkbox"
                        class="checkbox preset-tonal-warning border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500 border"
                        id="optout_publication_in_app"
                        name="optout_publication_in_app"
                        checked={$lq__event_presenter_obj.data_json
                            ?.optout_publication_in_app}
                        value={true} />
                    Opt-out - Publication of Presentation on LCI Congress App
                </label>

                <div class="w-full text-center">
                    <button
                        type="submit"
                        disabled={$events_sess.pres_mgmt
                            ?.disable_submit__opt_out}
                        onclick={() => {
                            console.log('*** Save button clicked ***');
                        }}
                        class="btn btn-md
                        preset-filled-secondary-50-950 preset-outlined-secondary-300-700
                        hover:preset-filled-secondary-400-600 m-2">
                        <Check size="1em" class="m-1 text-orange-700-300" />
                        Save Opt-Out?

                        {#await ae_promises.update__event_presenter_obj}
                            <div class="modal-loading">
                                <LoaderCircle size="1em" class="animate-spin" />
                                <span class="loading-text">
                                    <!-- <ProgressRadial value={undefined} /> -->
                                    Saving...
                                </span>
                            </div>
                        {:then update__event_presenter_obj_result}
                            {#if update__event_presenter_obj_result}
                                <div class="modal-loading">
                                    <CircleCheck size="1em" />
                                    <span class="loading-text"
                                        >Successfully saved!</span>
                                </div>
                            {/if}
                        {:catch error}
                            <div class="modal-loading">
                                <TriangleAlert size="1em" />
                                <span class="loading-text"
                                    >Error: {error.message}</span>
                            </div>
                        {/await}
                    </button>
                </div>
            </form>
        </div>

        <div class="w-full text-center">
            <h3 class="h4">Agree?</h3>
            <!-- Agree (agreement) means this presenter has agreed to the terms and conditions. -->
            {#if !$lq__event_presenter_obj?.agree}
                <div>
                    Not Agreed:
                    <X size="1em" class="m-1 text-error-500" />
                    <!-- <span class="fas fa-question text-red-500 m-1"></span> -->
                </div>
                <div>
                    Waiting for agreement to the Guest Speaker Consent and
                    Release and Terms and Conditions before you can move on.
                </div>
            {:else}
                <div>
                    Agreed:
                    <Check size="1em" class="m-1 text-success-500" />
                    Marked as agreed
                </div>
            {/if}

            {#if !$lq__event_presenter_obj?.agree}
                <button
                    type="button"
                    disabled={!$ae_loc.administrator_access &&
                        !events_auth_loc.current.auth__kv.presentation[
                            $lq__event_presenter_obj
                                ?.event_presentation_id
                        ]}
                    onclick={() => {
                        console.log('Agree to the terms and conditions.');

                        $events_sess.pres_mgmt.status__presenter_agree =
                            'saving';

                        let event_presenter_data = {
                            agree: true,
                            data_json: {
                                ...$lq__event_presenter_obj.data_json,
                                agree_updated_on: new Date().toISOString()
                            }
                        };

                        ae_promises.update__event_presenter_obj__agree =
                            events_func
                                .update_ae_obj__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presentation_id:
                                        $lq__event_presenter_obj?.event_presentation_id,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    data_kv: event_presenter_data,
                                    log_lvl: log_lvl
                                })
                                .then(function (update_result) {
                                    if (log_lvl) {
                                        console.log(
                                            'update_result:',
                                            update_result
                                        );
                                    }
                                    $events_sess.pres_mgmt.status__presenter_agree =
                                        'saved';
                                });
                    }}
                    class="btn btn-lg
                    preset-filled-primary-100-900
                    preset-outlined-primary-400-600
                    hover:preset-filled-success-400-600 m-2">
                    <Check size="1em" class="m-1 text-orange-500" />
                    Mark as agreed?

                    {#await ae_promises.update__event_presenter_obj__agree}
                        <div class="modal-loading">
                            <LoaderCircle size="1em" class="animate-spin" />
                            <span class="loading-text"> Saving... </span>
                        </div>
                    {:then update__event_presenter_obj__agree_result}
                        {#if $events_sess.pres_mgmt.status__presenter_agree}
                            <div class="modal-loading">
                                <CircleCheck size="1em" />
                                <span class="loading-text"
                                    >Successfully saved!</span>
                            </div>
                        {/if}
                    {:catch error}
                        <div class="modal-loading">
                            <TriangleAlert size="1em" />
                            <span class="loading-text"
                                >Error: {error.message}</span>
                        </div>
                    {/await}
                </button>
            {:else}
                <button
                    type="button"
                    disabled={!$ae_loc.administrator_access &&
                        !events_auth_loc.current.auth__kv.presentation[
                            $lq__event_presenter_obj
                                ?.event_presentation_id
                        ]}
                    onclick={() => {
                        console.log(
                            'Revoke agreement to the terms and conditions.'
                        );

                        $events_sess.pres_mgmt.status__presenter_agree =
                            'saving';

                        let event_presenter_data = {
                            agree: false,
                            data_json: {
                                ...$lq__event_presenter_obj.data_json,
                                agree_updated_on: new Date().toISOString()
                            }
                        };

                        ae_promises.update__event_presenter_obj__agree =
                            events_func
                                .update_ae_obj__event_presenter({
                                    api_cfg: $ae_api,
                                    event_presentation_id:
                                        $lq__event_presenter_obj?.event_presentation_id,
                                    event_presenter_id:
                                        $lq__event_presenter_obj?.event_presenter_id,
                                    data_kv: event_presenter_data,
                                    log_lvl: log_lvl
                                })
                                .then(function (update_result) {
                                    if (log_lvl) {
                                        console.log(
                                            'update_result:',
                                            update_result
                                        );
                                    }
                                    $events_sess.pres_mgmt.status__presenter_agree =
                                        'saved';
                                });
                    }}
                    class="btn btn-lg preset-tonal-warning border-warning-500 hover:preset-filled-error-500 m-2 border">
                    <X size="1em" class="m-1 text-orange-500" />
                    Change to not agreed?

                    {#await ae_promises.update__event_presenter_obj__agree}
                        <div class="modal-loading">
                            <LoaderCircle size="1em" class="animate-spin" />
                            <span class="loading-text"> Saving... </span>
                        </div>
                    {:then update__event_presenter_obj__agree_result}
                        {#if $events_sess.pres_mgmt.status__presenter_agree}
                            <div class="modal-loading">
                                <CircleCheck size="1em" />
                                <span class="loading-text"
                                    >Successfully saved!</span>
                            </div>
                        {/if}
                    {:catch error}
                        <div class="modal-loading">
                            <TriangleAlert size="1em" />
                            <span class="loading-text"
                                >Error: {error.message}</span>
                        </div>
                    {/await}
                </button>
            {/if}
        </div>
    </section>
{/if}
