"use client";
import { createEvent, deleteEvent, modifyEvent } from "@/app/api/events/actions";
import { useSchedule } from "@/app/schedule/context";
import Form from "next/form";
import { useState } from "react";

export function EventsEdit() {
	const schedule = useSchedule()!;
	const event = schedule.events[0];

	return <details>
		<summary>Admin Edit</summary>
		<h3>Create Event</h3>
		<Form action={createEvent}>
			<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" defaultValue="2025-07-20T18:00" />
			</label>
			<label>
				End:
				<input type="datetime-local" name="end" defaultValue="2025-07-20T20:00" />
			</label>
			<label>
				Location
				<select name="location">
					{schedule?.locations.map(location => <option key={location.id} value={location.id}>{location.name}</option>)}
				</select>
			</label>
			<button type="submit">Create</button>
		</Form>
		<h3>Edit Event</h3>
		<Form action={modifyEvent}>
			<label>
				Event
				<select name="id" onChange={(event) => {
					const newEvent = schedule.events.find(e => e.id === event.target.value)!;
					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];
						}
					}
				}}>
					{schedule?.events.map(event => <option key={event.id} value={event.id}>{event.name}</option>)}
				</select>
			</label>
			<label>
				Name:
				<input type="text" name="name" defaultValue={event.name} />
			</label>
			<label>
				Description:
				<textarea name="description" defaultValue={event.description} />
			</label>
			<label>
				Start:
				<input type="datetime-local" name="start" defaultValue={event.slots[0].start.replace("Z", "")} />
			</label>
			<label>
				End:
				<input type="datetime-local" name="end" defaultValue={event.slots[0].end.replace("Z", "")} />
			</label>
			<label>
				Location
				<select name="location">
					{schedule?.locations.map(location => <option key={location.id} value={location.id}>{location.name}</option>)}
				</select>
			</label>
			<button type="submit">Edit</button>
			<button type="submit" formAction={deleteEvent}>Delete</button>
		</Form>
	</details>;
}
