<script lang="ts">
	// *** 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 { core_func } from '$lib/ae_core/ae_core_functions';
	import {
		ae_snip,
		ae_loc,
		ae_sess,
		ae_api,
		ae_trig,
		slct,
		slct_trigger
	} from '$lib/stores/ae_stores';
	import {
		journals_loc,
		journals_sess,
		journals_slct,
		journals_trig,
		journals_prom
	} from '$lib/ae_journals/ae_journals_stores';
	import { journals_func } from '$lib/ae_journals/ae_journals_functions';

	import Comp_hosted_files_upload from '$lib/ae_core/ae_comp__hosted_files_upload.svelte';
	import Element_manage_hosted_file_li_wrap from '$lib/elements/element_manage_hosted_file_li_all.svelte';

	interface Props {
		log_lvl?: number;
		link_to_type: string;
		link_to_id: string;
		lq__journal_entry_obj: any;
	}

	let { log_lvl = 0, link_to_type, link_to_id, lq__journal_entry_obj }: Props = $props();

	let ae_promises: key_val = $state({});
	let hosted_file_kv: key_val = $state($lq__journal_entry_obj?.data_json?.hosted_file_kv ?? {}); // WARNING: This does no seem to set soon enough. Added an effect to set it as a backup.
	// let hosted_file_li: [string, any][] = $state([]);
	let slct_hosted_file_obj_li: any[] = $state(
		$lq__journal_entry_obj?.data_json?.slct_hosted_file_obj_li ?? []
	);
	let slct_hosted_file_id_li: string[] = $state([]);
	let upload_complete: boolean = $state(false);

	let slct_hosted_file_kv: key_val = $state({});
	let slct_hosted_file_id: string | null = $state(null);
	let slct_hosted_file_obj: any = $state(null);

	let rem_hosted_file_id: string | null = $state(null);

	async function update_journal_entry() {
		// hosted_file_kv = lq__journal_entry_obj.data_json.hosted_file_kv;
		// slct_hosted_file_obj_li = [... $lq__journal_entry_obj?.data_json?.slct_hosted_file_obj_li];
		// hosted_file_kv = {
		//     ...$lq__journal_entry_obj?.data_json?.hosted_file_kv,
		// };

		let data_kv: key_val = { data_json: $lq__journal_entry_obj?.data_json ?? {} };

		data_kv.data_json = {
			hosted_file_kv: hosted_file_kv
			// ...$lq__journal_entry_obj?.data_json,
			// hosted_file_kv: {
			//     ...slct_hosted_file_kv,
			// },
			// slct_hosted_file_obj_li: slct_hosted_file_obj_li
		};
		console.log('data_kv', data_kv);

		try {
			const response = await journals_func.update_ae_obj__journal_entry({
				api_cfg: $ae_api,
				journal_entry_id: $lq__journal_entry_obj?.journal_entry_id,
				data_kv: data_kv,
				log_lvl: 1
			});
			console.log('Journal entry updated successfully:', response);
		} catch (error) {
			console.error('Error updating journal entry:', error);
			alert('Failed to update journal entry.');
		}
	}

	$effect(() => {
		// if ($lq__journal_entry_obj && Object.keys(slct_hosted_file_kv ?? {}).length && slct_hosted_file_kv != hosted_file_kv) {
		//     hosted_file_kv = {
		//         hosted_file_kv,
		//         ...slct_hosted_file_kv
		//         };
		//     console.log('hosted_file_kv', hosted_file_kv);
		//     slct_hosted_file_kv = {};
		//     update_journal_entry();
		// }

		if (
			!Object.keys(hosted_file_kv ?? {}).length &&
			$lq__journal_entry_obj?.data_json?.hosted_file_kv
		) {
			hosted_file_kv = $lq__journal_entry_obj?.data_json?.hosted_file_kv;
		}

		// This is for the Select file option
		if ($lq__journal_entry_obj && slct_hosted_file_id && slct_hosted_file_obj) {
			if (log_lvl) {
				console.log(`slct_hosted_file_id=${slct_hosted_file_id}`, slct_hosted_file_obj);
			}
			hosted_file_kv = {
				...hosted_file_kv,
				[slct_hosted_file_id]: slct_hosted_file_obj
			};
			slct_hosted_file_id = null;
			slct_hosted_file_obj = null;

			update_journal_entry();

			// slct_hosted_file_obj = $lq__journal_entry_obj?.data_json?.slct_hosted_file_obj_li?.find((obj: any) => obj.hosted_file_id == slct_hosted_file_id);
			// console.log('slct_hosted_file_obj', slct_hosted_file_obj);
		}

		// This is for the Upload file option
		if (
			$lq__journal_entry_obj &&
			slct_hosted_file_id_li &&
			slct_hosted_file_id_li.length &&
			upload_complete
		) {
			if (log_lvl) {
				console.log(`slct_hosted_file_id=${slct_hosted_file_id}`, slct_hosted_file_obj);
			}

			hosted_file_kv = {
				...hosted_file_kv,
				// ...keymap
				// ...slct_hosted_file_kv
				...Object.fromEntries(slct_hosted_file_id_li.map((id) => [id, slct_hosted_file_kv[id]]))
			};
			slct_hosted_file_id = null;
			slct_hosted_file_obj = null;
			slct_hosted_file_id_li = [];

			upload_complete = false;

			update_journal_entry();

			// slct_hosted_file_obj = $lq__journal_entry_obj?.data_json?.slct_hosted_file_obj_li?.find((obj: any) => obj.hosted_file_id == slct_hosted_file_id);
			// console.log('slct_hosted_file_obj', slct_hosted_file_obj);
		}

		if ($lq__journal_entry_obj && rem_hosted_file_id) {
			if (log_lvl) {
				console.log(`rem_hosted_file_id=${rem_hosted_file_id}`);
			}

			delete hosted_file_kv[rem_hosted_file_id];
			rem_hosted_file_id = null;
			update_journal_entry(); // Should we use await here?
		}
	});
</script>

<section
	class:hidden={!$ae_loc.edit_mode}
	class="
        ae_section journal_entry__hosted_file
        border border-gray-200 rounded
        p-2 space-y-2
        w-full
        "
>
	<button
		type="button"
		class="btn btn-sm preset-tonal-warning border border-warning-500 hover:preset-filled-warning-500 float-right"
		title="Toggle between Upload and Select from Hosted Files"
		onclick={() => {
			if ($ae_sess.files.add_to_use_files_method == 'upload') {
				$ae_sess.files.add_to_use_files_method = 'select';
			} else {
				$ae_sess.files.add_to_use_files_method = 'upload';
			}
		}}
	>
		<span class="fas fa-exchange-alt m-1"></span>
		Upload/Select
	</button>

	<h3 class="h3 text-lg">
		{$ae_sess.files.add_to_use_files_method == 'select' ? 'Select' : 'Upload'} and Manage Hosted Files
	</h3>
	<!-- {Object.keys($lq__journal_entry_obj?.data_json?.hosted_file_kv ?? {}).length} selected -->
	<!-- {Object.keys(hosted_file_kv ?? {}).length} selected -->
	<!-- {Object.keys(slct_hosted_file_kv ?? {}).length} to add -->

	<div class:hidden={$ae_sess.files.add_to_use_files_method != 'upload'} class="upload">
		<Comp_hosted_files_upload
			class_li="
                        border border-gray-300 rounded-md p-2
                        bg-gray-100 dark:bg-gray-800
                        "
			{link_to_type}
			{link_to_id}
			bind:hosted_file_id_li={slct_hosted_file_id_li}
			bind:hosted_file_obj_li={slct_hosted_file_obj_li}
			bind:hosted_file_obj_kv={slct_hosted_file_kv}
			bind:upload_complete
			{log_lvl}
		>
			{#snippet label()}
				<span>
					<div>
						<span class="fas fa-upload"></span>
						<strong class="bg-green-100 dark:bg-green-900 p-1">Upload Journal Entry files</strong>
					</div>
					<span class="text-sm text-gray-600 dark:text-gray-400 italic">
						<strong>Aether hosted files only</strong>
					</span>
				</span>
			{/snippet}
		</Comp_hosted_files_upload>
	</div>

	<div class:hidden={$ae_sess.files.add_to_use_files_method != 'select'} class="">
		<!-- link_to_type={'journal_entry'} -->
		<!-- link_to_id={$lq__journal_entry_obj?.journal_entry_id} -->
		<Element_manage_hosted_file_li_wrap
			link_to_type={'account'}
			link_to_id={$ae_loc?.account_id}
			allow_basic={true}
			allow_moderator={true}
			class_li={''}
			bind:slct_hosted_file_kv
			bind:slct_hosted_file_id
			bind:slct_hosted_file_obj
		/>
	</div>

	{#if !Object.keys(hosted_file_kv ?? {}).length}
		No file(s) uploaded yet.
	{:else}
		<!-- {Object.keys(hosted_file_kv ?? {}).length} -->
		<!-- <pre>
    {JSON.stringify(hosted_file_kv)}
    </pre> -->

		{#each Object.entries(hosted_file_kv) as [hosted_file_id, hosted_file_obj]}
			<div class="flex flex-row flex-wrap gap-1 items-center justify-center w-full">
				<label for="filename" class="grow">
					<span class="text-sm text-gray-600 dark:text-gray-400 italic">
						<span class="fas fa-file-alt"></span>
						<strong class="bg-green-100 p-1">Filename</strong>
					</span>
					<input
						type="text"
						id="filename"
						name="filename"
						value={hosted_file_obj?.filename ? hosted_file_obj?.filename : 'unknown'}
						class="input w-full"
					/>
				</label>

				<label for="extension max-w-20">
					<span class="text-sm text-gray-600 dark:text-gray-400 italic">
						<span class="fas fa-file-code"></span>
						<strong class="bg-green-100 p-1">File Extension</strong>
						{#if !$ae_loc.administrator_access}
							<span class="fas fa-lock" title="Field is locked"></span>
						{:else}
							<span class="fas fa-unlock" title="Field is unlocked"></span>
						{/if}
					</span>
					<input
						type="text"
						id="extension"
						name="extension"
						value={hosted_file_obj?.extension ? hosted_file_obj?.extension : 'ext'}
						readonly={!$ae_loc.administrator_access}
						class="input w-full max-w-20"
					/>
				</label>

				<button
					disabled={!$ae_loc.administrator_access}
					type="button"
					onclick={async () => {
						if (confirm('Are you sure you want to remove the file?')) {
							// First - Attempt to delete the hosted file
							ae_promises.journal_entry_obj__hosted_file = await core_func
								.delete_ae_obj_id__hosted_file({
									api_cfg: $ae_api,
									hosted_file_id: hosted_file_id,
									link_to_type: link_to_type,
									link_to_id: link_to_id,
									rm_orphan: true,
									fake_delete: true,
									log_lvl: log_lvl
								})
								.then(function (delete_result) {
									// Second - If deleted, then update the journal_entry_obj
									console.log(`File removed. Now update the journal_entry_obj`);

									rem_hosted_file_id = hosted_file_id; // Should we use await here?
									// update_journal_entry();
								})
								.catch(function (error: any) {
									console.log('Something went wrong.');
									console.log(error);
									return false;
								})
								.finally(() => {
									// We need to do all of this since the DB object has changed and the SLCT object does automatically update (yet...??? Svelte 5?).
									slct_hosted_file_obj.hosted_file_id = null;
									slct_hosted_file_obj.file_path = null;
									slct_hosted_file_obj.filename = null;
									slct_hosted_file_obj.file_extension = null;
								});
						}
					}}
					class="btn btn-sm preset-tonal-error"
				>
					{#await ae_promises.journal_entry_obj__hosted_file}
						<span class="fas fa-spinner fa-spin m-1"></span>
					{:then}
						<span class="fas fa-trash-alt m-1"></span>
						Remove File
					{/await}
					<!-- <span class="fas fa-trash-alt m-1"></span>
                        Remove File -->
				</button>
			</div>
		{/each}

		<!-- <label for="file_path">File Path
            {#if !$ae_loc.administrator_access}
                <span class="fas fa-lock" title="Field is locked"></span>
            {:else}
                <span class="fas fa-unlock" title="Field is unlocked"></span>
            {/if}
            <input
                type="text"
                id="file_path"
                name="file_path"
                value={(slct_hosted_file_obj.file_path ? slct_hosted_file_obj.file_path : '')}
                readonly={!$ae_loc.administrator_access}
                class="input w-full"
                >
        </label> -->
	{/if}
</section>
