<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/api/api';
	import Element_data_store from '$lib/elements/element_data_store_v2.svelte';
	// import Element_ae_crud from '$lib/element_ae_crud.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_loc,
		events_sess,
		events_slct,
		events_trigger
	} from '$lib/stores/ae_events_stores';
	import { events_func } from '$lib/ae_events_functions';

	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 preventDefault<T extends Event>(fn: (event: T) => void) {
		return function (event: T) {
			event.preventDefault();
			fn(event);
		};
	}

	async function handle_submit_form(event) {
		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);
		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_random,
			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 }) {
		console.log('*** handle_update__event_presenter() ***');

		ae_promises.update__event_presenter_obj = api
			.update_ae_obj_id_crud({
				api_cfg: $ae_api,
				obj_type: obj_type,
				obj_id: obj_id,
				fields: data,
				key: $ae_api.api_crud_super_key,
				return_obj: true,
				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}
	<h2 class="h3">
		<span class="text-base">Presenter Agreement for:</span><br />
		<strong
			>{$lq__event_presenter_obj?.full_name}
			{#if $lq__event_presenter_obj?.person_primary_email}
				({$lq__event_presenter_obj?.person_primary_email ?? '-- not set --'})
			{/if}
		</strong>
	</h2>

	{#if !$lq__event_presenter_obj?.agree}
		<div class="text-center text-red-500">
			<div class="text-red-500">
				<span class="fas fa-times text-red-500 m-1"></span>
				Not Yet Agreed
			</div>
			<div class="bg-red-100 p-4 border border-red-200 rounded-md">
				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="bg-gray-100 p-4 border border-gray-200 rounded-md space-y-4">
		<Element_data_store ds_code="event_presenter_agree_text" ds_type="html" class_li="p-2" />
	</div>

	<section class="text-lg border border-red-200 rounded-md bg-red-100 space-y-2">
		<!-- Highlight the persons name, email, and that whole line. -->
		<p class="text-lg bg-yellow-100 p-2">
			<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={preventDefault(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 p-1 hover:preset-tonal-warning border border-warning-500 rounded-md"
					for="optout_audio"
				>
					<input
						type="checkbox"
						class="checkbox preset-tonal-warning border border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500"
						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 p-1 hover:preset-tonal-warning border border-warning-500 rounded-md"
					for="optout_video"
				>
					<input
						type="checkbox"
						class="checkbox preset-tonal-warning border border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500"
						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 p-1 hover:preset-tonal-warning border border-warning-500 rounded-md"
					for="optout_transcription_and_publication"
				>
					<input
						type="checkbox"
						class="checkbox preset-tonal-warning border border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500"
						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 p-1 hover:preset-tonal-warning border border-warning-500 rounded-md"
					for="optout_publication_in_app"
				>
					<input
						type="checkbox"
						class="checkbox preset-tonal-warning border border-warning-500 checked:preset-filled-warning-500 hover:preset-filled-error-500"
						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="text-center w-full">
					<button
						type="submit"
						disabled={$events_sess.pres_mgmt?.disable_submit__opt_out}
						onclick={() => {
							console.log('*** Save button clicked ***');
						}}
						class="btn btn-md preset-tonal-warning border border-warning-500 hover:preset-filled-secondary-500 m-2"
					>
						<span class="fas fa-check m-1 text-orange-500"></span>
						Save Opt-Out?

						{#await ae_promises.update__event_presenter_obj}
							<div class="modal-loading">
								<span class="fas fa-spinner fa-spin"></span>
								<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">
									<span class="fas fa-check-circle"></span>
									<span class="loading-text">Successfully saved!</span>
								</div>
							{/if}
						{:catch error}
							<div class="modal-loading">
								<span class="fas fa-exclamation-triangle"></span>
								<span class="loading-text">Error: {error.message}</span>
							</div>
						{/await}
					</button>
				</div>
			</form>
		</div>

		<div class="text-center w-full">
			<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:
					<span class="fas fa-times text-red-500 m-1"></span>
					<!-- <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:
					<span class="fas fa-check text-green-500 m-1"></span>
					Marked as agreed
				</div>
			{/if}

			{#if !$lq__event_presenter_obj?.agree}
				<button
					disabled={!$ae_loc.administrator_access &&
						!$events_loc.auth__kv.presentation[
							$lq__event_presenter_obj?.event_presentation_id_random
						]}
					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_presenter_id: $lq__event_presenter_obj?.event_presenter_id_random,
								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-primary border border-primary-500 hover:preset-filled-success-500 m-2"
				>
					<span class="fa fa-check m-1 text-orange-500"></span>
					Mark as agreed?

					{#await ae_promises.update__event_presenter_obj__agree}
						<div class="modal-loading">
							<span class="fas fa-spinner fa-spin"></span>
							<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">
								<span class="fas fa-check-circle"></span>
								<span class="loading-text">Successfully saved!</span>
							</div>
						{/if}
					{:catch error}
						<div class="modal-loading">
							<span class="fas fa-exclamation-triangle"></span>
							<span class="loading-text">Error: {error.message}</span>
						</div>
					{/await}
				</button>
			{:else}
				<button
					disabled={!$ae_loc.administrator_access &&
						!$events_loc.auth__kv.presentation[
							$lq__event_presenter_obj?.event_presentation_id_random
						]}
					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_presenter_id: $lq__event_presenter_obj?.event_presenter_id_random,
								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 border-warning-500 hover:preset-filled-error-500 m-2"
				>
					<span class="fas fa-times m-1 text-orange-500"></span>
					Change to not agreed?

					{#await ae_promises.update__event_presenter_obj__agree}
						<div class="modal-loading">
							<span class="fas fa-spinner fa-spin"></span>
							<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">
								<span class="fas fa-check-circle"></span>
								<span class="loading-text">Successfully saved!</span>
							</div>
						{/if}
					{:catch error}
						<div class="modal-loading">
							<span class="fas fa-exclamation-triangle"></span>
							<span class="loading-text">Error: {error.message}</span>
						</div>
					{/await}
				</button>
			{/if}
		</div>
	</section>
{/if}
