<template>
	<details>
		<summary>Admin Edit</summary>
		<h3>Create Event</h3>
		<form method="post" action="/api/create-event">
			<label>
				Id:
				<input type="text" name="id" required />
			</label>
			<label>
				Name:
				<input type="text" name="name" required />
			</label>
			<label>
				Description:
				<textarea name="description" />
			</label>
			<label>
				Start:
				<input type="datetime-local" name="start" required />
			</label>
			<label>
				End:
				<input type="datetime-local" name="end"  required/>
			</label>
			<label>
				Location
				<select name="location">
					<option
						v-for="location in schedule.locations"
						:key="location.id"
						:value="location.id"
					>{{ location.name }} </option>
				</select>
			</label>
			<button type="submit">Create</button>
		</form>
		<h3>Edit Event</h3>
		<form method="post" action="/api/modify-event">
			<label>
				Event
				<select name="id" @change="onChange" ref="eventSelect">
					<option
						v-for="event in schedule.events"
						:key="event.id"
						:value="event.id"
					>{{ event.name }}</option>
				</select>
			</label>
			<label>
				Name:
				<input type="text" name="name" required />
			</label>
			<label>
				Description:
				<textarea name="description" />
			</label>
			<label>
				Start:
				<input type="datetime-local" name="start" required />
			</label>
			<label>
				End:
				<input type="datetime-local" name="end" required />
			</label>
			<label>
				Location
				<select name="location">
					<option
						v-for="location in schedule.locations"
						:key="location.id"
						:value="location.id"
					>{{ location.name }} </option>
				</select>
			</label>
			<button type="submit">Edit</button>
			<button type="submit" formaction="/api/delete-event">Delete</button>
		</form>
	</details>
</template>

<script lang="ts" setup>
const schedule = useSchedule();
const eventSelect = useTemplateRef("eventSelect");

function onChange(event: any) {
	const newEvent = schedule.value.events.find(e => e.id === event.target.value);
	if (!newEvent)
		return;
	const form = event.target.form!;
	for (const element of form.elements as any) {
		if (element.name === "name") {
			element.value = newEvent.name;
		} else if (element.name === "description") {
			element.value = newEvent.description;
		} else if (element.name === "start") {
			element.value = newEvent.slots[0].start.replace("Z", "");
		} else if (element.name === "end") {
			element.value = newEvent.slots[0].end.replace("Z", "");
		} else if (element.name === "location") {
			element.value = newEvent.slots[0].locations[0];
		}
	}
}

onMounted(() => {
	onChange({ target: eventSelect.value });
})
</script>

<style>

</style>
