<template>
	<div v-if="schedule.deleted">
		Error: Unexpected deleted schedule.
	</div>
	<div v-else>
		<table>
			<thead>
				<tr>
					<th>id</th>
					<th>name</th>
					<th>description</th>
					<th>p</th>
					<th>s</th>
					<th v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<template v-if="edit">
					<tr
						v-for="event in events.filter(e => !e.deleted)"
						:key="event.id"
						:class="{ removed: removed.has(event.id) }"
					>
						<td>{{ event.id }}</td>
						<td>
							<input
								type="text"
								:value="event.name"
								:disabled="!canEdit(event)"
								@input="editEvent(event, { name: ($event as any).target.value })"
							>
						</td>
						<td>
							<input
								type="text"
								:disabled="!canEdit(event)"
								:value="event.description"
								@input="editEvent(event, { description: ($event as any).target.value })"
							>
						</td>
						<td>
							<input
								type="checkbox"
								:disabled="!accountStore.canEditPublic"
								:value="!event.crew"
								:checked="!event.crew"
								@change="editEvent(event, { crew: !($event as any).target.value })"
							>
						</td>
						<td>{{ event.slots.length ? event.slots.length : "" }}</td>
						<td>
							<button
								type="button"
								:disabled="!canEdit(event) || removed.has(event.id)"
								@click="delEvent(event.id)"
							>Delete</button>
							<button
								v-if="changes.some(c => c.id === event.id)"
								type="button"
								@click="revertEvent(event.id)"
							>Revert</button>
						</td>
					</tr>
					<tr>
						<td>{{ toId(newEventName) }}</td>
						<td>
							<input
								type="text"
								v-model="newEventName"
							>
						</td>
						<td>
							<input
								type="text"
								v-model="newEventDescription"
							>
						</td>
						<td>
							<input
								type="checkbox"
								:disabled="!accountStore.canEditPublic"
								v-model="newEventPublic"
							>
						</td>
						<td></td>
						<td>
							<button
								v-if="eventExists(newEventName)"
								disabled
							>Event already exists</button>
							<button
								v-else
								type="button"
								@click="newEvent"
							>Add Event</button>
						</td>
					</tr>
				</template>
				<template v-else>
					<tr
						v-for="event in events.filter(e => !e.deleted)"
						:key="event.id"
					>
						<td>{{ event.id }}</td>
						<td>{{ event.name }}</td>
						<td>{{ event.description }}</td>
						<td>{{ event.crew ? "" : "Yes"}}</td>
						<td>{{ event.slots.length ? event.slots.length : "" }}</td>
					</tr>
				</template>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not saved yet.
			<button
				type="button"
				@click="saveEvents"
			>Save Changes</button>
		</p>
		<details>
			<summary>Debug</summary>
			<ol>
				<li v-for="change in changes">
					{{ JSON.stringify(change) }}
				</li>
			</ol>
		</details>
	</div>
</template>

<script lang="ts" setup>
import type { ApiSchedule, ApiScheduleEvent } from '~/shared/types/api';
import { toId } from '~/shared/utils/functions';
import { applyUpdatesToArray } from '~/shared/utils/update';

defineProps<{
	edit?: boolean,
}>();

const schedule = await useSchedule();
const accountStore = useAccountStore();

function canEdit(event: ApiScheduleEvent) {
	return !event.deleted && (event.crew || accountStore.canEditPublic);
}

const changes = ref<ApiScheduleEvent[]>([]);
const removed = computed(() => new Set(changes.value.filter(c => c.deleted).map(c => c.id)));
function replaceChange(
	change: ApiScheduleEvent,
	changes: ApiScheduleEvent[],
) {
	const index = changes.findIndex(item => (
		item.deleted === change.deleted && item.id === change.id
	));
	const copy = [...changes];
	if (index !== -1)
		copy.splice(index, 1, change);
	else
		copy.push(change);
	return copy;
}
function revertChange(id: number, changes: ApiScheduleEvent[]) {
	return changes.filter(change => change.id !== id);
}

const newEventName = ref("");
const newEventDescription = ref("");
const newEventPublic = ref(false);
function editEvent(
	event: Extract<ApiScheduleEvent, { deleted?: false }>,
	edits: { name?: string, description?: string, crew?: boolean }
) {
	const copy = { ...event };
	if (edits.name !== undefined) {
		copy.name = edits.name;
	}
	if (edits.description !== undefined) {
		copy.description = edits.description || undefined;
	}
	if (edits.crew !== undefined) {
		copy.crew = edits.crew || undefined;
	}
	changes.value = replaceChange(copy, changes.value);
}
function delEvent(id: number) {
	const change = { id, updatedAt: "", deleted: true as const };
	changes.value = replaceChange(change, changes.value);
}
function revertEvent(id: number) {
	changes.value = revertChange(id, changes.value);
}
function eventExists(name: string) {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	name = toId(name);
	return (
		schedule.value.events?.some(e => !e.deleted && toId(e.name) === name)
		|| changes.value.some(c => !c.deleted && c.name === name)
	);
}
function newEvent() {
	if (eventExists(newEventName.value)) {
		alert(`Event ${newEventName.value} already exists`);
		return;
	}
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const id = Math.max(1, ...schedule.value.events?.map(e => e.id) ?? []) + 1;
	const change = {
		id,
		updatedAt: "",
		name: newEventName.value,
		description: newEventDescription.value || undefined,
		crew: !newEventPublic.value || undefined,
		slots: [],
	};
	changes.value = replaceChange(change, changes.value);
	newEventName.value = "";
	newEventDescription.value = "";
	newEventPublic.value = false;
}
async function saveEvents() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: {
				id: 111,
				updatedAt: "",
				events: changes.value,
			} satisfies ApiSchedule,
		});
		changes.value = [];
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}

const events = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const data = [...schedule.value.events ?? []];
	applyUpdatesToArray(changes.value.filter(change => !change.deleted), data);
	return data;
});
</script>

<style scoped>
table {
	border-spacing: 0;
}
table th {
	text-align: left;
	border-bottom: 1px solid var(--foreground);
}
table :is(th, td) + :is(th, td) {
	padding-inline-start: 0.4em;
}
.removed :is(td, input) {
	text-decoration: line-through;
}
</style>
