<template>
	<div>
		<table>
			<thead>
				<tr>
					<th>id</th>
					<th>name</th>
					<th>role</th>
					<th>s</th>
					<th>description</th>
					<th v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<template v-if="edit">
					<tr
						v-for="shift in shifts"
						:key="shift.id"
						:class="{ removed: removed.has(shift.id) }"
					>
						<td>{{ shift.id }}</td>
						<td>
							<input
								type="text"
								:value="shift.name"
								@input="editShift(shift, { name: ($event as any).target.value })"
							>
						</td>
						<td>
							<select
								:value="shift.role"
								@change="editShift(shift, { role: ($event as any).target.value })"
							>
								<option
									v-for="role in schedule.roles"
									:key="role.id"
									:value="role.id"
									:selected="shift.role === role.id"
								>{{ role.name }}</option>
							</select>
						</td>
						<td>{{ shift.slots.length ? shift.slots.length : "" }}</td>
						<td>
							<input
								type="text"
								:value="shift.description"
								@input="editShift(shift, { description: ($event as any).target.value })"
							>
						</td>
						<td>
							<button
								type="button"
								:disabled="removed.has(shift.id)"
								@click="delShift(shift.id)"
							>Delete</button>
							<button
								v-if="changes.some(c => c.data.id === shift.id)"
								type="button"
								@click="revertShift(shift.id)"
							>Revert</button>
						</td>
					</tr>
					<tr>
						<td>{{ toId(newShiftName) }}</td>
						<td>
							<input
								type="text"
								v-model="newShiftName"
							>
						</td>
						<td>
							<select v-model="newShiftRole">
								<option
									v-for="role in schedule.roles"
									:key="role.id"
									:value="role.id"
									:selected="role.id === newShiftRole"
								>{{ role.name }}</option>
							</select>
						</td>
						<td></td>
						<td>
							<input
								type="text"
								v-model="newShiftDescription"
							>
						</td>
						<td>
							<button
								v-if="shiftExists(newShiftName)"
								disabled
							>Shift already exists</button>
							<button
								v-else
								type="button"
								@click="newShift"
							>Add Shift</button>
						</td>
					</tr>
				</template>
				<template v-else>
					<tr
						v-for="shift in shifts"
						:key="shift.id"
					>
						<td>{{ shift.id }}</td>
						<td>{{ shift.name }}</td>
						<td>{{ shift.role }}</td>
						<td>{{ shift.slots.length ? shift.slots.length : "" }}</td>
						<td>{{ shift.description }}</td>
					</tr>
				</template>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not saved yet.
			<button
				type="button"
				@click="saveShifts"
			>Save Changes</button>
		</p>
		<details>
			<summary>Debug</summary>
			<ol>
				<li v-for="change in changes">
					<pre><code>{{ JSON.stringify(change, undefined, 2) }}</code></pre>
				</li>
			</ol>
		</details>
	</div>
</template>

<script lang="ts" setup>
import type { ChangeRecord, Shift } from '~/shared/types/schedule';
import { applyChangeArray } from '~/shared/utils/changes';
import { toId } from '~/shared/utils/functions';

const props = defineProps<{
	edit?: boolean,
	role?: string,
}>();

const schedule = await useSchedule();

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

const newShiftName = ref("");
const newShiftRole = ref(props.role);
watch(() => props.role, () => {
	newShiftRole.value = props.role;
});
const newShiftDescription = ref("");
function editShift(
	shift: Shift,
	edits: { name?: string, description?: string, role?: string }
) {
	const copy = { ...shift };
	if (edits.name !== undefined) {
		copy.name = edits.name;
	}
	if (edits.description !== undefined) {
		copy.description = edits.description || undefined;
	}
	if (edits.role !== undefined) {
		copy.role = edits.role;
	}
	const change = { op: "set" as const, data: copy };
	changes.value = replaceChange(change, changes.value);
}
function delShift(id: string) {
	const change = { op: "del" as const, data: { id } };
	changes.value = replaceChange(change, changes.value);
}
function revertShift(id: string) {
	changes.value = revertChange(id, changes.value);
}
function shiftExists(name: string) {
	const id = toId(name);
	return (
		schedule.value.rota?.some(e => e.id === id)
		|| changes.value.some(c => c.data.id === id)
	);
}
function newShift() {
	if (shiftExists(newShiftName.value)) {
		alert(`Shift ${newShiftName.value} already exists`);
		return;
	}
	if (!newShiftRole.value) {
		alert(`Invalid role`);
		return;
	}
	const change = {
		op: "set" as const,
		data: {
			id: toId(newShiftName.value),
			name: newShiftName.value,
			role: newShiftRole.value,
			description: newShiftDescription.value || undefined,
			slots: [],
		},
	};
	changes.value = replaceChange(change, changes.value);
	newShiftName.value = "";
	newShiftDescription.value = "";
}
async function saveShifts() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: { rota: changes.value },
		});
		changes.value = [];
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}

const shifts = computed(() => {
	const data = [...schedule.value.rota ?? []].filter(shift => !props.role || shift.role === props.role);
	applyChangeArray(changes.value.filter(change => change.op === "set"), 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>
