<script lang="ts">
	import { page } from '$app/state';
	import { onMount } from 'svelte';
	import QRCode from 'qrcode';

	let { data } = $props();
	let session_storage_id = page.url.searchParams.get('data');
	let all_data = {};

	const StepStatus = {
		Loading: 'loading',
		Waiting: 'waiting',
		Success: 'success',
		Failure: 'failure'
	} as const;
	type StepStatus = (typeof StepStatus)[keyof typeof StepStatus];
	let event_status: StepStatus = $state(StepStatus.Waiting);
	let participants_status: StepStatus = $state(StepStatus.Waiting);
	let email_status: StepStatus = $state(StepStatus.Waiting);

	let createdParticipants = $state([]);
	let mailStatuses = $state([]); // { email, name, status: 'pending' | 'success' | 'failure' }

	onMount(async () => {
		if (!session_storage_id) {
			console.error('No session storage ID provided in the URL');
			return;
		}
		all_data = JSON.parse(sessionStorage.getItem(session_storage_id) || '{}');

		try {
			let createdEvent;
			
			if (all_data.isAddingParticipants && all_data.existingEventId) {
				// Skip event creation for existing events
				event_status = StepStatus.Success;
				createdEvent = { id: all_data.existingEventId, ...all_data.event };
			} else {
				// Create new event
				event_status = StepStatus.Loading;
				createdEvent = await createEventInSupabase(all_data.event);
				event_status = StepStatus.Success;
			}

			participants_status = StepStatus.Loading;
			createdParticipants = await createParticipantsInSupabase(all_data.participants, createdEvent);
			participants_status = StepStatus.Success;

		} catch (e) {
			if (event_status === StepStatus.Loading) event_status = StepStatus.Failure;
			else participants_status = StepStatus.Failure;
			console.error(e);
		}
	});

	async function createEventInSupabase(event) {
		console.log('Creating event in Supabase:', event);
		const { data: createdEvent, error: eventError } = await data.supabase.rpc('create_event', {
			p_name: event.name,
			p_date: event.date
		});
		console.log('Created event:', createdEvent);
		if (eventError) throw eventError;
		return createdEvent;
	}

	async function createParticipantsInSupabase(participants, event) {
		const names = participants.map((p) => p.name);
		const surnames = participants.map((p) => p.surname);
		const emails = participants.map((p) => p.email);
		const {
			data: { user },
			error: authError
		} = await data.supabase.auth.getUser();
		const { data: user_profile, error: profileError } = await data.supabase
			.from('profiles')
			.select('*, section:sections (id, name)')
			.eq('id', user?.id)
			.single();
		const { data: result, error: qrCodeError } = await data.supabase.rpc('create_qrcodes_bulk', {
			p_section_id: user_profile?.section.id,
			p_event_id: event.id,
			p_names: names,
			p_surnames: surnames,
			p_emails: emails
		});
		if (qrCodeError) throw qrCodeError;
		return result;
	}

	async function sendEmails(participants, email) {
		mailStatuses = participants.map((p) => ({ email: p.email, name: `${p.name} ${p.surname}`, status: 'pending' }));
		let allSuccess = true;
		for (let i = 0; i < participants.length; i++) {
			const obj = participants[i];
			let qr_code = await dataToBase64(obj.id);
			const payload = {
				action: 'send',
				to: obj.email,
				subject: email.subject,
				text: email.body,
				qr_code: qr_code,
				refreshToken: localStorage.getItem('gmail_refresh_token')
			};
			try {
				const res = await fetch('/private/api/gmail', {
					method: 'POST',
					headers: { 'Content-Type': 'application/json' },
					body: JSON.stringify(payload)
				});
				if (res.ok) {
					mailStatuses[i].status = 'success';
				} else {
					mailStatuses[i].status = 'failure';
					allSuccess = false;
					console.error('Failed to send email to', obj.email, await res.text());
				}
			} catch (e) {
				mailStatuses[i].status = 'failure';
				allSuccess = false;
				console.error('Failed to send email to', obj.email, e);
			}
		}
		return allSuccess;
	}

	async function dataToBase64(data: string): Promise<string> {
		try {
			const url = await QRCode.toDataURL(data);
			const parts = url.split(',');
			const base64 = parts[1];
			return base64;
		} catch (err) {
			console.error(err);
			return '';
		}
	}

	async function launchMailCampaign() {
		email_status = StepStatus.Loading;
		try {
			const allSuccess = await sendEmails(createdParticipants, all_data.email);
			email_status = allSuccess ? StepStatus.Success : StepStatus.Failure;
		} catch (e) {
			email_status = StepStatus.Failure;
			console.error(e);
		}
	}
</script>

<!-- Creating Event Entry -->
<div class="mb-4 rounded border border-gray-300 bg-white p-4">
	<h2 class="mb-2 text-xl font-bold">
		{all_data.isAddingParticipants ? 'Using existing event' : 'Creating event'}
	</h2>
	{#if event_status === StepStatus.Waiting}
		<span class="text-black-600">Waiting...</span>
	{:else if event_status === StepStatus.Loading}
		<span class="text-black-600">Creating event...</span>
	{:else if event_status === StepStatus.Success}
		<span class="text-green-600">
			{all_data.isAddingParticipants ? 'Using existing event.' : 'Event created successfully.'}
		</span>
	{:else if event_status === StepStatus.Failure}
		<span class="text-red-600">Failed to create event.</span>
	{/if}
</div>

<!-- Creating Database Entries -->
<div class="mb-4 rounded border border-gray-300 bg-white p-4">
	<h2 class="mb-2 text-xl font-bold">Creating QR codes for participants</h2>
	{#if participants_status === StepStatus.Waiting}
		<span class="text-black-600">Waiting...</span>
	{:else if participants_status === StepStatus.Loading}
		<span class="text-black-600">Creating entries...</span>
	{:else if participants_status === StepStatus.Success}
		<span class="text-green-600">QR codes created successfully.</span>
	{:else if participants_status === StepStatus.Failure}
		<span class="text-red-600">Failed to create QR codes.</span>
	{/if}
</div>

<!-- Sending Emails -->
<div class="rounded border border-gray-300 bg-white p-4">
	<h2 class="mb-1 text-xl font-bold">Sending emails</h2>
	<p class="text-sm text-red-500 mb-2">After pressing send, you must not exit this window until the mail are all sent!</p>
	{#if email_status === StepStatus.Waiting}
		<div class="flex items-center justify-between">
			<span class="text-black-600">Waiting...</span>
			<button
				disabled={event_status !== StepStatus.Success || participants_status !== StepStatus.Success}
				onclick={launchMailCampaign}
				class="ml-4 px-6 py-2 rounded font-semibold transition disabled:opacity-50 disabled:cursor-not-allowed
					{event_status === StepStatus.Success && participants_status === StepStatus.Success ? 'bg-blue-600 hover:bg-blue-700 text-white' : 'bg-gray-400 text-white'}"
			>
				Send all emails
			</button>
		</div>
	{:else}
		<ul class="mt-4 space-y-2">
			{#each createdParticipants as p, i}
				<li class="flex items-center border-b pb-1 gap-2">
					{#if mailStatuses[i]?.status === 'success'}
						<svg
							title="Sent"
							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 if mailStatuses[i]?.status === 'failure'}
						<svg
							title="Failed"
							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>
					{:else}
						<svg
							title="Pending"
							class="mr-2 inline h-4 w-4 text-gray-400"
							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" />
						</svg>
					{/if}
					<span class="font-semibold">{p.name} {p.surname}</span>
					<span class="font-mono text-xs text-gray-600 ml-auto">{p.email}</span>
				</li>
			{/each}
		</ul>
		{#if email_status === StepStatus.Loading}
			<span class="block mt-2 text-black-600">Sending emails...</span>
		{:else if email_status === StepStatus.Success}
			<span class="block mt-2 text-green-600">Emails sent successfully.</span>
		{:else if email_status === StepStatus.Failure}
			<span class="block mt-2 text-red-600">Failed to send emails.</span>
		{/if}
	{/if}
</div>
