<script lang="ts">
	import Button from "$lib/components/ui/button/button.svelte";
	import * as Card from "$lib/components/ui/card";
	import {
		fetchEvents,
		type DAVCalendar,
		type DAVCredentials,
		type DAVEvent,
	} from "$lib/services/CalDAV";
	import { search } from "$lib/services/Search";
	import { onMount } from "svelte";
	import { map, pin } from "../map.svelte";
	import { m } from "$lang/messages";

	let events: DAVEvent[] = $state([]);

	onMount(async () => {
		const calendars = localStorage.getItem("calendars");
		if (!calendars) return;
		const parsedCalendars: (DAVCalendar & { credentials: DAVCredentials })[] =
			JSON.parse(calendars);
		for (const calendar of parsedCalendars) {
			const calendarEvents = await fetchEvents(calendar, calendar.credentials);
			events.push(...calendarEvents);
		}
	});
</script>

<div id="events">
	{#each events as event ((event.start + "" || "") + (event.end + "" || ""))}
		<Card.Root>
			<Card.Header>
				<Card.Title>{event.summary}</Card.Title>
				{#if event.description}
					<Card.Description>{event.description}</Card.Description>
				{/if}
			</Card.Header>
			<Card.Content>
				<p>
					<strong>{m["calendar.start"]()}:</strong>
					{event.start?.toLocaleString("de-DE") || m["calendar.no-start"]()}
				</p>
				<p>
					<strong>{m["calendar.end"]()}:</strong>
					{event.end?.toLocaleString("de-DE") || m["calendar.no-end"]()}
				</p>
				<p>
					{#if event.location}
						<strong>{m["calendar.location"]()}:</strong> {event.location}
					{:else}
						<strong>{m["calendar.location"]()}:</strong>
						{m["calendar.no-location"]()}
					{/if}
				</p>
			</Card.Content>
			<Card.Footer>
				<Button
					onclick={async () => {
						if (!event.location) return;
						const features = await search(event.location, 0, 0);
						if (features.length == 0) {
							return void alert("Can't find location");
						}
						const lat = features[0].geometry.coordinates[1];
						const lng = features[0].geometry.coordinates[0];
						pin.dropPin(lat, lng);
						pin.showInfo();
						map.value?.flyTo({
							center: [lng, lat],
							zoom: 19,
						});
					}}>{m.open()}</Button
				>
			</Card.Footer>
		</Card.Root>
	{/each}
</div>

<style>
	#events {
		display: flex;
		flex-direction: column;
		gap: 0.5rem;
	}
</style>
