<script lang="ts">
	import Papa from 'papaparse';

	let { participants = $bindable() } = $props();
	let showForm = $derived(participants.length === 0);
	let errors = $state([]);

	function isValidEmail(email: string): boolean {
		return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
	}

	async function handleSubmit(e: Event) {
		e.preventDefault();
		errors = [];
		const form = e.target as HTMLFormElement;
		const fileInput = form.elements.namedItem('participants') as HTMLInputElement;
		const file = fileInput?.files?.[0];
		if (!file) return;
		const csvText = await file.text();
		const { data: parsedRows } = Papa.parse<string[]>(csvText, {
			skipEmptyLines: true,
			header: false
		});
		// Remove the first row (header)
		if (parsedRows.length > 0) {
			parsedRows.shift();
		}
		const validated = [];
		parsedRows.forEach((row, idx) => {
			if (!row || row.length < 3) {
				errors.push(`Row ${idx + 2} is missing columns.`);
				return;
			}
			const [name, surname, email] = row;
			if (!name || !surname || !email) {
				errors.push(`Row ${idx + 2} has missing values.`);
				return;
			}
			validated.push({
				name,
				surname,
				email,
				email_valid: isValidEmail(email)
			});
		});
		if (errors.length > 0) {
			return; // Do not proceed if there are errors
		}
		if (validated.length === 0) {
			participants = [];
			return;
		}
		participants = validated.sort((a, b) => {
			if (a.email_valid === b.email_valid) return 0;
			return a.email_valid ? 1 : -1;
		});
		showForm = false;
	}

	function showEditForm() {
		showForm = true;
	}
</script>

{#if showForm}
	{#if errors.length > 0}
		<div class="mb-4 rounded border border-red-400 bg-red-50 p-4 text-red-700">
			<ul class="list-disc ml-4">
				{#each errors as err}
					<li>{err}</li>
				{/each}
			</ul>
		</div>
	{/if}
	<form
		onsubmit={handleSubmit}
		autocomplete="off"
		enctype="multipart/form-data"
		class="flex w-full flex-col space-y-4 rounded border border-gray-300 bg-white p-8 shadow-none"
	>
		<h2 class="mb-4 text-center text-2xl font-semibold">Upload Participants</h2>
		<label class="flex flex-col text-gray-700">
			CSV File
			<input
				type="file"
				name="participants"
				id="participants"
				accept=".csv"
				class="mt-1 rounded border border-gray-300 px-3 py-2 focus:ring-2 focus:ring-blue-200 focus:outline-none"
				required
			/>
		</label>
		<button
			type="submit"
			class="w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
		>
			Submit
		</button>
	</form>
{:else}
	<button
		class="w-full rounded bg-blue-600 py-2 text-white transition hover:bg-blue-700"
		onclick={showEditForm}
		aria-label="Edit participants"
	>
		Edit participants
	</button>
{/if}

{#if !showForm}
	<div class="mt-4 rounded border border-gray-300 bg-white p-4">
		<div class="mb-2 flex items-center justify-between">
			<h2 class="text-xl font-bold">Participants ({participants.length})</h2>
			{#if participants.length > 0}
				{#if participants.some((p) => !p.email_valid)}
					<span class="text-xs text-gray-500">Some emails appear invalid</span>
				{:else}
					<span class="text-xs text-gray-500">All emails appear valid</span>
				{/if}
			{/if}
		</div>

		<ul class="space-y-1">
			{#each participants as p}
				<li class="flex items-center gap-2 border-b pb-1 last:border-b-0">
					{#if p.email_valid}
						<svg
							title="Valid email"
							class="mr-2 inline h-4 w-4 text-green-600"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							viewBox="0 0 24 24"
						>
							<path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" />
						</svg>
					{:else}
						<svg
							title="Invalid email"
							class="mr-2 inline h-4 w-4 text-red-600"
							fill="none"
							stroke="currentColor"
							stroke-width="2"
							viewBox="0 0 24 24"
						>
							<circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2" fill="none" />
							<line x1="8" y1="8" x2="16" y2="16" stroke="currentColor" stroke-width="2" />
							<line x1="16" y1="8" x2="8" y2="16" stroke="currentColor" stroke-width="2" />
						</svg>
					{/if}
					<span class="font-semibold">{p.name} {p.surname}</span>
					<span class="flex-1"></span>
					<span class="text-right font-mono text-xs text-gray-600">{p.email}</span>
				</li>
			{/each}
		</ul>
	</div>
{/if}
