<script lang="ts">
	import { goto } from '$app/navigation';
	import summary from '$lib/shared/stores/summary';
	import Fa from 'svelte-fa/src/fa.svelte';
	import { faTrashCan } from '@fortawesome/free-regular-svg-icons';

	let files: FileList | null;
	let url: string = '';
	let fileForm: HTMLFormElement;
	let hasFile = true;
	let loading = false;

	$: if (files && files.length >= 0) {
		hasFile = true;
		url = '';
	} else {
		hasFile = false;
	}

	const removeFile = () => {
		fileForm.reset();
		hasFile = false;
	};

	const submitUrl = async (url: string) => {
		const formData = new FormData();
		formData.append('url', url);
		return submit(formData);
	};

	const submitFile = async (file: File) => {
		const formData = new FormData();
		formData.append('file', file);
		return submit(formData);
	};

	const submit = async (formData: FormData) => {
		const response = await fetch('/', {
			method: 'POST',
			body: formData
		});
		return await response.json();
	};

	const summarize = async () => {
		try {
			loading = true;
			let result;
			if (hasFile) {
				if (!files) throw new Error('File missing');
				if (files.length <= 0) throw new Error('File missing');
				result = await submitFile(files[0]);
			} else {
				result = await submitUrl(url);
			}
			summary.set(JSON.stringify(result.response));
			loading = false;
			return goto('chat');
		} catch (error) {
			alert((error as App.Error).message);
			console.error(`Error: ${JSON.stringify(error)}`);
		}
	};
</script>

<div class="container h-full mx-auto flex justify-center items-center px-4">
	<div class="text-center">
		{#if loading}
			<p>Please wait while Sumi tries to make sense of this garbage.</p>
		{:else}
			<h2>Please Sumi</h2>
			<p class="my-4">Enter the URL you'd like to have summarized.</p>
			<div>
				<input
					class="input"
					type="text"
					bind:value={url}
					disabled={hasFile}
					placeholder="https://stupid.article/you-will-never-believe-this-shit"
				/>
			</div>
			<p class="my-6">•</p>
			<div>
				<p>Or you can submit a text file instead:</p>
				<form bind:this={fileForm}>
					<div class="flex flex-row">
						<input class="input my-4" type="file" accept=".txt" name="conversation" bind:files />
						{#if hasFile}
							<button
								type="button"
								class="btn btn-icon-sm variant-ghost-error self-center"
								style="height: 100%;"
								on:click={removeFile}
								><Fa icon={faTrashCan} />
							</button>
						{/if}
					</div>
				</form>
			</div>
			<div class="flex justify-center space-x-2 my-12">
				<button
					type="button"
					class="btn variant-ringed-tertiary"
					disabled={!hasFile && url.length <= 0}
					on:click={summarize}>Summarize</button
				>
			</div>
		{/if}
	</div>
</div>
