<template>
	<figure>
		<table>
			<thead>
				<tr>
					<th>id</th>
					<th>name</th>
					<th>description</th>
					<th v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<tr
					v-for="location in locations.filter(l => !l.deleted)"
					:key="location.id"
					:class="{ removed: removed.has(location.id) }"
				>
					<template v-if='edit'>
						<td>{{ location.id }}</td>
						<td>
							<input
								type="text"
								:value="location.name"
								@input="setLocation({ ...location, name: ($event as any).target.value })"
							>
						</td>
						<td>
							<input
								type="text"
								:value="location.description"
								@input="setLocation({ ...location, description: ($event as any).target.value || undefined })"
							>
						</td>
						<td>
							<button
								:disabled="removed.has(location.id)"
								type="button"
								@click="delLocation(location.id)"
							>Remove</button>
							<button
								v-if="changes.some(c => c.id === location.id)"
								type="button"
								@click="revertLocation(location.id)"
							>Revert</button>
						</td>
					</template>
					<template v-else>
						<td>{{ location.id }}</td>
						<td>{{ location.name }}</td>
						<td>{{ location.description }}</td>
					</template>
				</tr>
				<tr v-if='edit'>
					<td>
						{{ newLocationId }}
					</td>
					<td>
							<input
								type="text"
								v-model="newLocationName"
							>
					</td>
					<td colspan="2">
						<button
							type="button"
							@click="newLocation(newLocationName); newLocationName = ''"
						>Add Location</button>
					</td>
				</tr>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not save yet.
			<button
				type="button"
				@click="saveLocations"
			>Save Changes</button>
		</p>
		<details>
			<summary>Debug</summary>
			<ol>
				<li v-for="change in changes">
					{{ JSON.stringify(change) }}
				</li>
			</ol>
		</details>
	</figure>
</template>

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

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

const schedule = await useSchedule();

const changes = ref<ApiScheduleLocation[]>([]);
const removed = computed(() => new Set(changes.value.filter(c => c.deleted).map(c => c.id)));

function replaceChange(
	change: ApiScheduleLocation,
	changes: ApiScheduleLocation[],
) {
	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: ApiScheduleLocation[]) {
	return changes.filter(change => change.id !== id);
}

const newLocationName = ref("");
const newLocationId = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	return Math.max(
		1,
		...schedule.value.locations?.map(l => l.id) ?? [],
		...changes.value.map(c => c.id)
	) + 1;
});
function setLocation(location: ApiScheduleLocation) {
	changes.value = replaceChange(location, changes.value);
}
function delLocation(id: number) {
	const change = { id, updatedAt: "", deleted: true as const };
	changes.value = replaceChange(change, changes.value);
}
function revertLocation(id: number) {
	changes.value = revertChange(id, changes.value);
}
function newLocation(name: string) {
	const change = {
		id: newLocationId.value,
		updatedAt: "",
		name,
	};
	changes.value = replaceChange(change, changes.value);
}
async function saveLocations() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: {
				id: 111,
				updatedAt: "",
				locations: changes.value
			} satisfies ApiSchedule,
		});
		changes.value = [];
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}

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