<script lang="ts">
	import { createEventDispatcher, onMount } from 'svelte';
	import { MessageType } from '$lib/types';

	export let inputEl: HTMLInputElement;
	export let disabled: boolean = true;

	const dispatch = createEventDispatcher();

	let textInput: string = '';
	let isDragOver: boolean = false;

	function onSubmit(event: Event) {
		event.stopPropagation();
		event.preventDefault();
		event.stopImmediatePropagation();
		if (textInput.trim() !== '') {
			dispatch('submitMessage', {
				type: MessageType.TEXT,
				content: textInput
			});
			textInput = '';
		}
	}
	function onDrop(event: DragEvent) {
		event.stopPropagation();
		event.preventDefault();
		event.stopImmediatePropagation();
		if (event && event.dataTransfer) {
			const files = [...event.dataTransfer.files];
			if (files.length) {
				const file = files[0];
				if (file.type.startsWith('image/') && file.size < 1.5e7) {
					const reader = new FileReader();
					reader.readAsDataURL(file);
					reader.onload = () => {
						dispatch('submitMessage', {
							type: MessageType.IMAGE,
							content: reader.result
						});
					};
				}
			}
		}
		isDragOver = false;
	}

	function onDragover(event: DragEvent) {
		event.stopPropagation();
		event.preventDefault();
		if (event && event.dataTransfer) {
			event.dataTransfer.dropEffect = 'copy';
		}
		isDragOver = true;
	}

	onMount(() => {
		inputEl.focus();
		window.addEventListener('dragover', onDragover, false);
		window.addEventListener('drop', onDrop, false);
		window.addEventListener('dragleave', () => (isDragOver = false), false);
	});
</script>

<div class="mt-auto {isDragOver ? 'bg-yellow-50' : ''} py-4">
	<form class="flex selection:w-full gap-2 border-t px-3 pt-4 pb-6" on:submit={onSubmit}>
		<input
			bind:value={textInput}
			bind:this={inputEl}
			on:click|stopPropagation
			{disabled}
			type="text"
			class="flex h-11 flex-1 items-center rounded-full border bg-gray-100 px-4 text-black disabled:opacity-60 disabled:cursor-progress"
			placeholder="Type here"
			title="Type here to send a message"
		/>
		<button
			{disabled}
			title="Send your message"
			type="submit"
			class="rounded-full bg-black dark:bg-white dark:text-black px-4 font-semibold text-gray-200 disabled:opacity-60 disabled:cursor-progress"
			>Submit</button
		>
	</form>
	<div class="flex items-center px-3 pt-4 pb-6 bg-yellow-50 py-3 rounded">
		<i class="fas fa-image text-2xl text-gray-500 mr-2" />
		<h2 class="text-xl font-bold text-gray-500">Drop your image here to start</h2>
	</div>
</div>
