<template>
	<div v-if="schedule.deleted">
		Error: Unexpected deleted schedule.
	</div>
	<div v-else>
		<Timetable :schedule="schedulePreview" :eventSlotFilter :shiftSlotFilter />
		<table>
			<thead>
				<tr>
					<th>start</th>
					<th>end</th>
					<th>duration</th>
					<th>shift</th>
					<th>s</th>
					<th>role</th>
					<th>assigned</th>
					<th v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<template v-if="edit">
					<tr
						v-for="ss in shiftSlots"
						:key='ss.slot?.id ?? ss.start.toMillis()'
						:class='{
							removed: ss.type === "slot" && removed.has(ss.id),
							gap: ss.type === "gap",
						}'
					>
						<template v-if="ss.type === 'gap'">
							<td colspan="2">
								{{ gapFormat(ss) }}
								gap
							</td>
							<td>
								<input
									type="time"
									v-model="newShiftDuration"
								>
							</td>
							<td>
									<input
										type="text"
										v-model="newShiftName"
									>
							</td>
							<td></td>
							<td>
								<select
									v-model="newShiftRole"
								>
									<option
										v-for="role in schedule.roles?.filter(r => !r.deleted)"
										:key="role.id"
										:value="role.id"
										:selected="role.id === newShiftRole"
									>{{ role.name }}</option>
								</select>
							</td>
							<td></td>
							<td>
								Add at
								<button
									type="button"
									@click="newShiftSlot({ start: ss.start })"
								>Start</button>
								<button
									type="button"
									@click="newShiftSlot({ end: ss.end })"
								>End</button>
							</td>
						</template>
						<template v-else-if='edit'>
							<td>
								<input
									type="datetime-local"
									:value="ss.start.toFormat('yyyy-LL-dd\'T\'HH:mm')"
									@blur="editShiftSlot(ss, { start: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="time"
									:value="ss.end.toFormat('HH:mm')"
									@input="editShiftSlot(ss, { end: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="time"
									:value='dropDay(ss.end.diff(ss.start)).toFormat("hh:mm")'
									@input="editShiftSlot(ss, { duration: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="text"
									:value="ss.name"
									@input="editShiftSlot(ss, { name: ($event as any).target.value })"
								>
							</td>
							<td>{{ status(ss) }}</td>
							<td>
								<select
									:value="ss.roleId"
									@change="editShiftSlot(ss, { roleId: parseInt(($event as any).target.value) })"
								>
									<option
										v-for="role in schedule.roles?.filter(r => !r.deleted)"
										:key="role.id"
										:value="role.id"
										:selected="role.id === ss.roleId"
									>{{ role.name }}</option>
								</select>
							</td>
							<td>
								<AssignedCrew
									:edit="true"
									:modelValue="ss.assigned"
									@update:modelValue="editShiftSlot(ss, { assigned: $event })"
								/>
							</td>
							<td>
								<button
									:disabled="removed.has(ss.id)"
									type="button"
									@click="delShiftSlot(ss)"
								>Remove</button>
								<button
									v-if="changes.some(c => c.id === ss.id)"
									type="button"
									@click="revertShiftSlot(ss.id)"
								>Revert</button>
							</td>
						</template>
					</tr>
					<tr>
						<td>
							<input
								type="datetime-local"
								v-model="newShiftStart"
							>
						</td>
						<td>
							<input
								type="time"
								v-model="newShiftEnd"
							>
						</td>
						<td>
							<input
								type="time"
								v-model="newShiftDuration"
							>
						</td>
						<td>
								<input
									type="text"
									v-model="newShiftName"
								>
						</td>
						<td colspan="3">
							<button
								type="button"
								@click="newShiftSlot()"
							>Add Shift</button>
						</td>
					</tr>
				</template>
				<template v-else>
					<tr
						v-for="ss in shiftSlots"
						:key='ss.slot?.id ?? ss.start.toMillis()'
						:class='{
							gap: ss.type === "gap",
						}'
					>
						<template v-if="ss.type === 'gap'">
							<td colspan="2">
								{{ gapFormat(ss) }}
								gap
							</td>
						</template>
						<template v-else>
							<td>{{ ss.start.toFormat("yyyy-LL-dd HH:mm") }}</td>
							<td>{{ ss.end.toFormat("HH:mm") }}</td>
							<td>{{ ss.end.diff(ss.start).toFormat('hh:mm') }}</td>
							<td>{{ ss.name }}</td>
							<td>{{ status(ss) }}</td>
							<td>{{ ss.roleId }}</td>
							<td><AssignedCrew :modelValue="ss.assigned" :edit="false" /></td>
						</template>
					</tr>
				</template>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not save yet.
			<button
				type="button"
				@click="saveShiftSlots"
			>Save Changes</button>
		</p>
		<details>
			<summary>Debug</summary>
			<b>ShiftSlot changes</b>
			<ol>
				<li v-for="change in changes">
					<pre><code>{{ JSON.stringify((({ shift, slot, ...data }) => data)(change as any), undefined, "  ") }}</code></pre>
				</li>
			</ol>
			<b>Shift changes</b>
			<ol>
				<li v-for="change in shiftChanges">
					<pre><code>{{ JSON.stringify((({ shift, slot, ...data }) => data)(change as any), undefined, "  ") }}</code></pre>
				</li>
			</ol>
		</details>
	</div>
</template>

<script lang="ts" setup>
import { DateTime, Duration } from 'luxon';
import type { ApiSchedule, ApiScheduleEventSlot, ApiScheduleShift, ApiScheduleShiftSlot } from '~/shared/types/api';
import { applyUpdatesToArray } from '~/shared/utils/update';
import { enumerate, pairs } from '~/shared/utils/functions';
import type { Entity } from '~/shared/types/common';

const props = defineProps<{
	edit?: boolean,
	roleId?: number,
	eventSlotFilter?: (slot: ApiScheduleEventSlot) => boolean,
	shiftSlotFilter?: (slot: ApiScheduleShiftSlot) => boolean,
}>();

interface ShiftSlot {
	type: "slot",
	id: number,
	updatedAt: string,
	deleted?: boolean,
	shift?: Extract<ApiScheduleShift, { deleted?: false }>,
	slot?: ApiScheduleShiftSlot,
	origRole: number,
	name: string,
	roleId: number,
	assigned: number[],
	start: DateTime,
	end: DateTime,
}

interface Gap {
	type: "gap",
	id?: undefined,
	shift?: undefined,
	slot?: undefined,
	name?: undefined,
	roleId?: number,
	start: DateTime,
	end: DateTime,
}

function status(shiftSlot: ShiftSlot) {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	if (
		!shiftSlot.shift
		|| shiftSlot.shift.name !== shiftSlot.name
	) {
		const shift = schedule.value.shifts?.find(shift => !shift.deleted && shift.name === shiftSlot.name);
		return shift ? "L" : "N";
	}
	return shiftSlot.shift.slots.length === 1 ? "" : shiftSlot.shift.slots.length;
}

// Filter out set records where a del record exists for the same id.
function filterSetOps<T extends Entity>(changes: T[]) {
	const deleteIds = new Set(changes.filter(c => c.deleted).map(c => c.id));
	return changes.filter(c => c.deleted || !deleteIds.has(c.id));
}

function findShift(
	shiftSlot: ShiftSlot,
	changes: ApiScheduleShift[],
	schedule: ApiSchedule,
) {
	if (schedule.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	let setShift = changes.filter(
		c => !c.deleted,
	).find(
		c => (
			c.name === shiftSlot.name
			&& c.roleId === shiftSlot.roleId
		)
	);
	if (
		!setShift
		&& shiftSlot.shift
		&& shiftSlot.shift.name === shiftSlot.name
	) {
		setShift = shiftSlot.shift;
	}
	if (!setShift) {
		setShift = schedule.shifts?.filter(s => !s.deleted).find(s => s.name === shiftSlot.name);
	}
	let delShift;
	if (shiftSlot.shift) {
		delShift = changes.filter(c => !c.deleted).find(
			c => c.name === shiftSlot.shift!.name
		);
		if (!delShift) {
			delShift = schedule.shifts?.filter(s => !s.deleted).find(s => s.name === shiftSlot.shift!.name);
		}
	}
	return { setShift, delShift };
}

function mergeSlot(
	shift: Extract<ApiScheduleShift, { deleted?: false }>,
	shiftSlot: ShiftSlot,
): Extract<ApiScheduleShift, { deleted?: false }> {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const oldSlot = shift.slots.find(s => s.id === shiftSlot.id);
	const nextId = Math.max(0, ...schedule.value.shifts?.filter(s => !s.deleted).flatMap(s => s.slots.map(slot => slot.id)) ?? []) + 1;
	const start = shiftSlot.start.toUTC().toISO({ suppressSeconds: true })!;
	const end = shiftSlot.end.toUTC().toISO({ suppressSeconds: true })!;
	const assigned = shiftSlot.assigned.length ? shiftSlot.assigned : undefined;

	if (shift.roleId !== shiftSlot.roleId) {
		console.warn(`Attempt to add slot id=${shiftSlot.id} roleId=${shiftSlot.roleId} to shift id=${shift.id} roleId=${shift.roleId}`);
	}

	// Edit slot in-place if possible
	if (oldSlot && oldSlot.id === shiftSlot.id) {
		return {
			...shift,
			slots: shift.slots.map(s => s.id !== oldSlot.id ? s : { ...s, assigned, start, end, }),
		};
	}

	// Else remove old slot if it exist and insert a new one
	return {
		...shift,
		slots: [...(oldSlot ? shift.slots.filter(s => s.id !== oldSlot.id) : shift.slots), {
			id: oldSlot ? oldSlot.id : nextId,
			assigned,
			start,
			end,
		}],
	};
}

const shiftChanges = computed(() => {
	let eventChanges: Extract<ApiScheduleShift, { deleted?: false }>[] = [];
	for (const change of filterSetOps(changes.value)) {
		if (!change.deleted) {
			let { setShift, delShift } = findShift(change, eventChanges, schedule.value);
			if (delShift && delShift !== setShift) {
				eventChanges = removeSlot(eventChanges, delShift, change);
			}
			if (!setShift) {
				setShift = {
					id: Math.floor(Math.random() * -1000), // XXX This wont work.
					updatedAt: "",
					name: change.name,
					roleId: change.roleId,
					slots: [],
				};
			}
			setShift = {
				...setShift,
				roleId: change.roleId,
			}

			eventChanges = replaceChange(mergeSlot(setShift, change), eventChanges);

		} else if (change.deleted) {
			let { delShift } = findShift(change, eventChanges, schedule.value);
			if (delShift) {
				eventChanges = removeSlot(eventChanges, delShift, change);
			}
		}
	}
	return eventChanges;
});

const schedulePreview = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const shifts = [...schedule.value.shifts ?? []]
	applyUpdatesToArray(shiftChanges.value, shifts);
	return {
		...schedule.value,
		shifts,
	};
});

function removeSlot(
	eventChanges: Extract<ApiScheduleShift, { deleted?: false }>[],
	shift: Extract<ApiScheduleShift, { deleted?: false }>,
	shiftSlot: ShiftSlot,
) {
	let oldSlot = shift.slots.find(s => s.id === shiftSlot.id);
	if (oldSlot) {
		eventChanges = replaceChange({
			...shift,
			slots: shift.slots.filter(s => s.id !== oldSlot.id)
		}, eventChanges);
	}
	return eventChanges;
}

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

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

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

const oneDayMs = 24 * 60 * 60 * 1000;
function dropDay(diff: Duration) {
	if (diff.toMillis() >= oneDayMs) {
		return diff.minus({ days: 1 });
	}
	return diff;
}

const newShiftStart = ref("");
const newShiftDuration = ref("01:00");
const newShiftEnd = computed({
	get: () => (
		DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" })
			.plus(Duration.fromISOTime(newShiftDuration.value, { locale: "en-US" }))
			.toFormat("HH:mm")
	),
	set: (value: string) => {
		const start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" });
		const end = endFromTime(start, value);
		newShiftDuration.value = dropDay(end.diff(start)).toFormat("hh:mm");
	},
});
const newShiftRole = ref(props.roleId);
watch(() => props.roleId, () => {
	newShiftRole.value = props.roleId;
});

function endFromTime(start: DateTime, time: string) {
	let end = start.startOf("day").plus(Duration.fromISOTime(time, { locale: "en-US" }));
	if (end.toMillis() <= start.toMillis()) {
		end = end.plus({ days: 1 });
	}
	return end;
}
function durationFromTime(time: string) {
	let duration = Duration.fromISOTime(time, { locale: "en-US" });
	if (duration.toMillis() === 0) {
		duration = Duration.fromMillis(oneDayMs, { locale: "en-US" });
	}
	return duration;
}
const newShiftName = ref("");
function editShiftSlot(
	shiftSlot: ShiftSlot,
	edits: {
		start?: string,
		end?: string,
		duration?: string,
		name?: string,
		roleId?: number,
		assigned?: number[],
	}
) {
	if (edits.start) {
		const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone, locale: "en-US" });
		shiftSlot = {
			...shiftSlot,
			start,
			end: start.plus(shiftSlot.end.diff(shiftSlot.start)),
		};
	}
	if (edits.end !== undefined) {
		shiftSlot = {
			...shiftSlot,
			end: endFromTime(shiftSlot.start, edits.end),
		};
	}
	if (edits.duration !== undefined) {
		shiftSlot = {
			...shiftSlot,
			end: shiftSlot.start.plus(durationFromTime(edits.duration)),
		};
	}
	if (edits.name !== undefined) {
		shiftSlot = {
			...shiftSlot,
			name: edits.name,
		};
	}
	if (edits.roleId !== undefined) {
		let changesCopy = changes.value;
		for (const slot of shiftSlots.value) {
			if (slot.type === "slot" && slot.shift?.name === shiftSlot.name) {
				changesCopy = replaceChange({
					...slot,
					roleId: edits.roleId,
				}, changesCopy);
			}
		}
		changesCopy = replaceChange({
			...shiftSlot,
			roleId: edits.roleId,
		}, changesCopy);
		changes.value = changesCopy;
		return;
	}
	if (edits.assigned !== undefined) {
		shiftSlot = {
			...shiftSlot,
			assigned: edits.assigned,
		};
	}
	changes.value = replaceChange(shiftSlot, changes.value);
}
function delShiftSlot(shiftSlot: ShiftSlot) {
	const change = {
		...shiftSlot,
		deleted: true,
	};
	changes.value = replaceChange(change, changes.value);
}
function revertShiftSlot(id: number) {
	changes.value = revertChange(id, changes.value);
}
function newShiftSlot(options: { start?: DateTime, end?: DateTime } = {}) {
	const name = newShiftName.value;
	const roleId = newShiftRole.value;
	if (!roleId) {
		alert("Invalid role");
		return;
	}
	let start;
	let end;
	const duration = durationFromTime(newShiftDuration.value);
	if (!duration.isValid) {
		alert("Invalid duration");
		return;
	}
	if (options.start) {
		start = options.start;
		end = options.start.plus(duration);
	} else if (options.end) {
		end = options.end;
		start = options.end.minus(duration);
	} else {
		start = DateTime.fromISO(newShiftStart.value, { zone: accountStore.activeTimezone, locale: "en-US" });
		end = endFromTime(start, newShiftEnd.value);
	}
	if (!start.isValid || !end.isValid) {
		alert("Invalid start and/or end time");
		return;
	}
	const change: ShiftSlot = {
		type: "slot",
		updatedAt: "",
		id: Math.floor(Math.random() * -1000), // XXX this wont work.
		name,
		origRole: roleId,
		roleId,
		assigned: [],
		start,
		end,
	};
	newShiftName.value = "";
	changes.value = replaceChange(change, changes.value);
}
async function saveShiftSlots() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: {
				id: 111,
				updatedAt: "",
				shifts: shiftChanges.value
			} satisfies ApiSchedule,
		});
		changes.value = [];
	} catch (err: any) {
		console.error(err);
		alert(err?.data?.message ?? err.message);
	}
}

const oneHourMs = 60 * 60 * 1000;
function gapFormat(gap: Gap) {
	let diff = gap.end.diff(gap.start);
	if (diff.toMillis() % oneHourMs !== 0)
		diff = diff.shiftTo("hours", "minutes");
	else
		diff = diff.shiftTo("hours");
	return diff.toHuman({ listStyle: "short", unitDisplay: "short" });
}

const shiftSlots = computed(() => {
	if (schedule.value.deleted) {
		throw new Error("Unexpected deleted schedule");
	}
	const data: (ShiftSlot | Gap)[] = [];
	for (const shift of schedule.value.shifts ?? []) {
		if (shift.deleted || props.roleId !== undefined && shift.roleId !== props.roleId)
			continue;
		for (const slot of shift.slots) {
			if (props.shiftSlotFilter && !props.shiftSlotFilter(slot))
				continue;
			data.push({
				type: "slot",
				id: slot.id,
				updatedAt: "",
				shift,
				slot,
				name: shift.name,
				roleId: shift.roleId,
				assigned: slot.assigned ?? [],
				origRole: shift.roleId,
				start: DateTime.fromISO(slot.start, { zone: accountStore.activeTimezone, locale: "en-US" }),
				end: DateTime.fromISO(slot.end, { zone: accountStore.activeTimezone, locale: "en-US" }),
			});
		}
	}
	applyUpdatesToArray(changes.value.filter(c => !c.deleted), data as ShiftSlot[]);
	data.sort((a, b) => a.start.toMillis() - b.start.toMillis() || a.end.toMillis() - b.end.toMillis());

	// Insert gaps
	let maxEnd = 0;
	const gaps: [number, Gap][] = []
	for (const [index, [first, second]] of enumerate(pairs(data))) {
		maxEnd = Math.max(maxEnd, first.end.toMillis());
		if (maxEnd < second.start.toMillis()) {
			gaps.push([index, {
				type: "gap",
				roleId: props.roleId,
				start: DateTime.fromMillis(maxEnd, { locale: "en-US" }),
				end: second.start,
			}]);
		}
	}
	gaps.reverse();
	for (const [index, gap] of gaps) {
		data.splice(index + 1, 0, gap);
	}
	return data;
});
</script>

<style scoped>
label {
	display: inline;
	padding-inline-end: 0.75em;
}
table {
	margin-block-start: 1rem;
	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;
}
.gap {
	height: 1.8em;
}
.removed {
	background-color: color-mix(in oklab, var(--background), rgb(255, 0, 0) 40%);
}
.removed :is(td, input) {
	text-decoration: line-through;
}
</style>
