<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 v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<template v-if="edit">
					<tr
						v-for="role in roles.filter(r => !r.deleted)"
						:key="role.id"
						:class="{ removed: removed.has(role.id) }"
					>
						<td>{{ role.id }}</td>
						<td>
							<input
								type="text"
								:value="role.name"
								@input="editRole(role, { name: ($event as any).target.value })"
							>
						</td>
						<td>
							<input
								type="text"
								:value="role.description"
								@input="editRole(role, { description: ($event as any).target.value })"
							>
						</td>
						<td>
							<button
								type="button"
								:disabled="removed.has(role.id)"
								@click="delRole(role.id)"
							>Delete</button>
							<button
								v-if="changes.some(c => c.id === role.id)"
								type="button"
								@click="revertRole(role.id)"
							>Revert</button>
						</td>
					</tr>
					<tr>
						<td>{{ newRoleId }}</td>
						<td>
							<input
								type="text"
								v-model="newRoleName"
							>
						</td>
						<td>
							<input
								type="text"
								v-model="newRoleDescription"
							>
						</td>
						<td>
							<button
								v-if="roleExists(newRoleName)"
								disabled
							>Role already exists</button>
							<button
								v-else
								type="button"
								@click="newRole"
							>Add Role</button>
						</td>
					</tr>
				</template>
				<template v-else>
					<tr
						v-for="role in roles.filter(r => !r.deleted)"
						:key="role.id"
					>
						<td>{{ role.id }}</td>
						<td>{{ role.name }}</td>
						<td>{{ role.description }}</td>
					</tr>
				</template>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not saved yet.
			<button
				type="button"
				@click="saveRoles"
			>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, ApiScheduleRole } from '~/shared/types/api';
import { applyUpdatesToArray } from '~/shared/utils/update';
import { toId } from '~/shared/utils/functions';

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

const schedule = await useSchedule();

const changes = ref<ApiScheduleRole[]>([]);
const removed = computed(() => new Set(changes.value.filter(c => c.deleted).map(c => c.id)));
function replaceChange(
	change: ApiScheduleRole,
	changes: ApiScheduleRole[],
) {
	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: ApiScheduleRole[]) {
	return changes.filter(change => change.id !== id);
}

const newRoleName = ref("");
const newRoleId = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	return Math.max(
		1,
		...schedule.value.roles?.map(r => r.id) ?? [],
		...changes.value.map(c => c.id)
	) + 1;
});
const newRoleDescription = ref("");
function editRole(
	role: Extract<ApiScheduleRole, { deleted?: false }>,
	edits: { name?: string, description?: string }
) {
	const copy = { ...role };
	if (edits.name !== undefined) {
		copy.name = edits.name;
	}
	if (edits.description !== undefined) {
		copy.description = edits.description || undefined;
	}
	changes.value = replaceChange(copy, changes.value);
}
function delRole(id: number) {
	const change = { id, updatedAt: "", deleted: true as const };
	changes.value = replaceChange(change, changes.value);
}
function revertRole(id: number) {
	changes.value = revertChange(id, changes.value);
}
function roleExists(name: string) {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	name = toId(name);
	return (
		schedule.value.roles?.some(r => !r.deleted && toId(r.name) === name)
		|| changes.value.some(c => !c.deleted && c.name === name)
	);
}
function newRole() {
	if (roleExists(newRoleName.value)) {
		alert(`Role ${newRoleName.value} already exists`);
		return;
	}
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const change = {
		id: newRoleId.value,
		updatedAt: "",
		name: newRoleName.value,
		description: newRoleDescription.value || undefined,
		slots: [],
	};
	changes.value = replaceChange(change, changes.value);
	newRoleName.value = "";
	newRoleDescription.value = "";
}
async function saveRoles() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: {
				id: 111,
				updatedAt: "",
				roles: changes.value
			} satisfies ApiSchedule,
		});
		changes.value = [];
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}

const roles = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const data = [...schedule.value.roles ?? []];
	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>
