<script lang="ts">
interface Props {
    log_lvl?: number;
    // Exports
    lq__event_session_obj: any;
}

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

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

// Imports (external and then internal)
import type { key_val } from '$lib/stores/ae_stores';
import { ae_util } from '$lib/ae_utils/ae_utils';
import {
    ae_loc,
    ae_sess,
    ae_api,
    ae_trig,
    slct,
    slct_trigger
} from '$lib/stores/ae_stores';
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_auth_loc } from '$lib/stores/ae_events_stores__auth.svelte';
import { events_func } from '$lib/ae_events/ae_events_functions';

// Import components and elements
import Element_data_store from '$lib/elements/element_data_store.svelte';
import {
    Check,
    CircleCheck,
    LoaderCircle,
    TriangleAlert,
    X
} from '@lucide/svelte';
// Local Variables
let ae_promises: key_val = $state({});
// let ae_tmp: key_val = {};
// let ae_triggers: key_val = {};

let poc_type = pres_mgmt_loc.current.label__session_poc_type ?? 'poc';

$events_sess.pres_mgmt.disable__session_submit_opt_out = false;
$events_sess.pres_mgmt.status__session_opt_out = null;
$events_sess.pres_mgmt.status__session_agree = null;

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__session_submit_opt_out = true;
    $events_sess.pres_mgmt.status__session_opt_out = '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);

    // poc_kv_json may be null if no POC data has been saved yet — initialize before writing.
    const kv: key_val = { ...(lq__event_session_obj.poc_kv_json ?? {}) };
    if (!kv[poc_type]) kv[poc_type] = {};
    kv[poc_type] = { ...kv[poc_type], ...opt_out_do };

    let event_session_data = { poc_kv_json: kv };

    // Use this in the future if we need to store the agreements in a more complex way?
    // let event_session_data = {poc_kv_json: lq__event_session_obj?.poc_kv_json};
    // console.log('event_session_data:', event_session_data);
    // event_session_data.poc_kv_json[poc_type]['agree'] = false;

    ae_promises.update__event_session_obj__opt_out = events_func
        .update_ae_obj__event_session({
            api_cfg: $ae_api,
            event_session_id: lq__event_session_obj?.event_session_id,
            data_kv: event_session_data,
            log_lvl: log_lvl
        })
        .then(function (update_result) {
            // console.log(update_result);
            // return update_result;
        });

    $events_sess.pres_mgmt.disable__session_submit_opt_out = false;
    $events_sess.pres_mgmt.status__session_opt_out = 'saved';
}
</script>

{#if lq__event_session_obj}
    {#if !lq__event_session_obj?.poc_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 {pres_mgmt_loc.current.label__session_poc_name} 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_session_poc_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_session_obj?.poc_agree}
        class:preset-filled-surface-400-600={!lq__event_session_obj?.poc_agree}
        class:border-success-300-700={lq__event_session_obj?.poc_agree}
        class:preset-tonal-success={lq__event_session_obj?.poc_agree}>
        <!-- Highlight the persons name, email, and that whole line. -->
        <p class="rounded-md p-2 text-lg"
           class:preset-tonal-warning={!lq__event_session_obj?.poc_agree}
           class:preset-tonal-success={lq__event_session_obj?.poc_agree}>
            {#if lq__event_session_obj?.poc_agree}
                <Check size="1em" class="mr-1 inline text-success-700" />
            {/if}
            <strong
                >{lq__event_session_obj.poc_person_full_name} ({lq__event_session_obj.poc_person_primary_email})</strong>
            agrees to the following terms and conditions for the presentation:
        </p>
        <h3 class="h4 text-center">
            <span class="text-base">Session:</span>
            "{lq__event_session_obj?.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_session_obj.poc_kv_json?.[poc_type]
                            ?.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_session_obj.poc_kv_json?.[poc_type]
                            ?.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_session_obj.poc_kv_json?.[poc_type]
                            ?.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_session_obj.poc_kv_json?.[poc_type]
                            ?.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__session_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_session_obj__opt_out}
                            <div class="modal-loading">
                                <LoaderCircle size="1em" class="animate-spin" />
                                <span class="loading-text"> Saving... </span>
                            </div>
                        {:then update__event_session_obj__opt_out_result}
                            {#if $events_sess.pres_mgmt.status__session_opt_out}
                                <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_session_obj?.poc_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 POC 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_session_obj?.poc_agree}
                <button
                    type="button"
                    disabled={!$ae_loc.administrator_access &&
                        !events_auth_loc.current.auth__kv.session[
                            lq__event_session_obj?.event_session_id
                        ] === true}
                    onclick={() => {
                        console.log('Agree to the terms and conditions.');

                        $events_sess.pres_mgmt.status__session_agree = 'saving';

                        let event_session_data = {
                            poc_agree: true
                        };

                        // Use this in the future if we need to store the agreements in a more complex way?
                        // let event_session_data = {poc_kv_json: lq__event_session_obj?.poc_kv_json};
                        // console.log('event_session_data:', event_session_data);
                        // event_session_data.poc_kv_json[poc_type]['agree'] = true;

                        ae_promises.update__event_session_obj__agree =
                            events_func
                                .update_ae_obj__event_session({
                                    api_cfg: $ae_api,
                                    event_session_id:
                                        lq__event_session_obj?.event_session_id,
                                    data_kv: event_session_data,
                                    log_lvl: log_lvl
                                })
                                .then(function (update_result) {
                                    if (log_lvl) {
                                        console.log(
                                            'update_result:',
                                            update_result
                                        );
                                    }
                                    $events_sess.pres_mgmt.status__session_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_session_obj__agree}
                        <div class="modal-loading">
                            <LoaderCircle size="1em" class="animate-spin" />
                            <span class="loading-text"> Saving... </span>
                        </div>
                    {:then update__event_session_obj__agree_result}
                        {#if $events_sess.pres_mgmt.status__session_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"
                    onclick={() => {
                        console.log('Change to not agreed.');

                        let event_session_data = {
                            poc_agree: false
                        };

                        // Use this in the future if we need to store the agreements in a more complex way?
                        // let event_session_data = {poc_kv_json: lq__event_session_obj?.poc_kv_json};
                        // console.log('event_session_data:', event_session_data);
                        // event_session_data.poc_kv_json[poc_type]['agree'] = false;

                        ae_promises.update__event_session_obj__agree =
                            events_func
                                .update_ae_obj__event_session({
                                    api_cfg: $ae_api,
                                    event_session_id:
                                        lq__event_session_obj?.event_session_id,
                                    data_kv: event_session_data,
                                    log_lvl: log_lvl
                                })
                                .then(function (update_result) {
                                    // console.log(update_result);
                                    // return update_result;
                                });
                    }}
                    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_session_obj__agree}
                        <div class="modal-loading">
                            <LoaderCircle size="1em" class="animate-spin" />
                            <span class="loading-text"> Saving... </span>
                        </div>
                    {:then update__event_session_obj__agree_result}
                        {#if $events_sess.pres_mgmt.status__session_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>
{:else}
    Not ready
{/if}
