<template>
	<div>
		<Timetable :schedule="schedulePreview" :eventSlotFilter :shiftSlotFilter />
		<table>
			<thead>
				<tr>
					<th>start</th>
					<th>end</th>
					<th>duration</th>
					<th>event</th>
					<th>s</th>
					<th>location</th>
					<th>assigned</th>
					<th v-if="edit"></th>
				</tr>
			</thead>
			<tbody>
				<template v-if="edit">
					<tr
						v-for="es in eventSlots"
						:key='es.slot?.id ?? es.start.toMillis()'
						:class='{
							removed: es.type === "slot" && removed.has(es.id),
							gap: es.type === "gap",
						}'
					>
						<template v-if="es.type === 'gap'">
							<td colspan="2">
								{{ gapFormat(es) }}
								gap
							</td>
							<td>
								<input
									type="time"
									v-model="newEventDuration"
								>
							</td>
							<td>
									<input
										type="text"
										v-model="newEventName"
									>
							</td>
							<td></td>
							<td>
								<select
									v-model="newEventLocation"
								>
									<option
										v-for="location in schedule.locations"
										:key="location.id"
										:value="location.id"
										:selected="location.id === newEventLocation"
									>{{ location.name }}</option>
								</select>
							</td>
							<td></td>
							<td>
								Add at
								<button
									type="button"
									@click="newEventSlot({ start: es.start })"
								>Start</button>
								<button
									type="button"
									@click="newEventSlot({ end: es.end })"
								>End</button>
							</td>
						</template>
						<template v-else-if='edit'>
							<td>
								<input
									type="datetime-local"
									:value="es.start.toFormat('yyyy-LL-dd\'T\'HH:mm')"
									@blur="editEventSlot(es, { start: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="time"
									:value="es.end.toFormat('HH:mm')"
									@input="editEventSlot(es, { end: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="time"
									:value='dropDay(es.end.diff(es.start)).toFormat("hh:mm")'
									@input="editEventSlot(es, { duration: ($event as any).target.value })"
								>
							</td>
							<td>
								<input
									type="text"
									:value="es.name"
									@input="editEventSlot(es, { name: ($event as any).target.value })"
								>
							</td>
							<td>{{ status(es) }}</td>
							<td>
								<select
									:value="es.location"
									@change="editEventSlot(es, { location: ($event as any).target.value })"
								>
									<option
										v-for="location in schedule.locations"
										:key="location.id"
										:value="location.id"
										:selected="location.id === es.location"
									>{{ location.name }}</option>
								</select>
							</td>
							<td>
								<AssignedCrew
									:edit="true"
									:modelValue="es.assigned"
									@update:modelValue="editEventSlot(es, { assigned: $event })"
								/>
							</td>
							<td>
								<button
									:disabled="removed.has(es.id)"
									type="button"
									@click="delEventSlot(es)"
								>Remove</button>
								<button
									v-if="changes.some(c => c.data.id === es.id)"
									type="button"
									@click="revertEventSlot(es.id)"
								>Revert</button>
							</td>
						</template>
					</tr>
					<tr>
						<td>
							<input
								type="datetime-local"
								v-model="newEventStart"
							>
						</td>
						<td>
							<input
								type="time"
								v-model="newEventEnd"
							>
						</td>
						<td>
							<input
								type="time"
								v-model="newEventDuration"
							>
						</td>
						<td>
								<input
									type="text"
									v-model="newEventName"
								>
						</td>
						<td></td>
						<td></td>
						<td colspan="2">
							<button
								type="button"
								@click="newEventSlot()"
							>Add Event</button>
						</td>
					</tr>
				</template>
				<template v-else>
					<tr
						v-for="es in eventSlots"
						:key='es.slot?.id ?? es.start.toMillis()'
						:class='{
							gap: es.type === "gap",
						}'
					>
						<template v-if="es.type === 'gap'">
							<td colspan="2">
								{{ gapFormat(es) }}
								gap
							</td>
						</template>
						<template v-else>
							<td>{{ es.start.toFormat("yyyy-LL-dd HH:mm") }}</td>
							<td>{{ es.end.toFormat("HH:mm") }}</td>
							<td>{{ es.end.diff(es.start).toFormat('hh:mm') }}</td>
							<td>{{ es.name }}</td>
							<td>{{ status(es) }}</td>
							<td>{{ es.location }}</td>
							<td><AssignedCrew :modelValue="es.assigned" :edit="false" /></td>
						</template>
					</tr>
				</template>
			</tbody>
		</table>
		<p v-if="changes.length">
			Changes are not save yet.
			<button
				type="button"
				@click="saveEventSlots"
			>Save Changes</button>
		</p>
		<details>
			<summary>Debug</summary>
			<b>EventSlot changes</b>
			<ol>
				<li v-for="change in changes">
					<pre><code>{{ JSON.stringify((({ event, slot, ...data }) => ({ op: change.op, data }))(change.data as any), undefined, "  ") }}</code></pre>
				</li>
			</ol>
			<b>ScheduleEvent changes</b>
			<ol>
				<li v-for="change in scheduleChanges">
					<pre><code>{{ JSON.stringify((({ event, slot, ...data }) => ({ op: change.op, data }))(change.data as any), undefined, "  ") }}</code></pre>
				</li>
			</ol>
		</details>
	</div>
</template>

<script lang="ts" setup>
import { DateTime, Duration } from 'luxon';
import type { ChangeRecord, Schedule, ScheduleEvent, ScheduleLocation, ShiftSlot, TimeSlot } from '~/shared/types/schedule';
import { applyChangeArray } from '~/shared/utils/changes';
import { enumerate, pairs, toId } from '~/shared/utils/functions';

const props = defineProps<{
	edit?: boolean,
	location?: string,
	eventSlotFilter?: (slot: TimeSlot) => boolean,
	shiftSlotFilter?: (slot: ShiftSlot) => boolean,
}>();

interface EventSlot {
	type: "slot",
	id: string,
	event?: ScheduleEvent,
	slot?: TimeSlot,
	origLocation: string,
	name: string,
	location: string,
	assigned: number[],
	start: DateTime,
	end: DateTime,
}

interface Gap {
	type: "gap",
	id?: undefined,
	event?: undefined,
	slot?: undefined,
	name?: undefined,
	location?: string,
	start: DateTime,
	end: DateTime,
}

function status(eventSlot: EventSlot) {
	if (
		!eventSlot.event
		|| eventSlot.event.name !== eventSlot.name
	) {
		const event = schedule.value.events.find(event => event.name === eventSlot.name);
		return event ? "L" : "N";
	}
	return eventSlot.event.slots.length === 1 ? "" : eventSlot.event.slots.length;
}

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

function findEvent(
	eventSlot: EventSlot,
	changes: ChangeRecord<ScheduleEvent>[],
	schedule: Schedule,
) {
	let setEvent = changes.find(
		c => c.op === "set" && c.data.name === eventSlot.name
	)?.data as ScheduleEvent | undefined;
	if (!setEvent && eventSlot.event && eventSlot.event.name === eventSlot.name) {
		setEvent = eventSlot.event;
	}
	if (!setEvent) {
		setEvent = schedule.events.find(e => e.name === eventSlot.name);
	}
	let delEvent;
	if (eventSlot.event) {
		delEvent = changes.find(
			c => c.op === "set" && c.data.name === eventSlot.event!.name
		)?.data as ScheduleEvent | undefined;
		if (!delEvent) {
			delEvent = schedule.events.find(e => e.name === eventSlot.event!.name);
		}
	}
	return { setEvent, delEvent };
}

function removeSlotLocation(event: ScheduleEvent, oldSlot: TimeSlot, location: string) {
	// If location is an exact match remove the whole slot
	if (oldSlot.locations.length === 1 && oldSlot.locations[0] === location) {
		return {
			...event,
			slots: event.slots.filter(s => s.id !== oldSlot.id),
		};
	}
	// Otherwise filter out location
	return {
		...event,
		slots: event.slots.map(
			s => s.id !== oldSlot.id ? s : {
				...s,
				locations: s.locations.filter(l => l !== location)
			}
		),
	};
}

function mergeSlot(event: ScheduleEvent, eventSlot: EventSlot): ScheduleEvent {
	const oldSlot = event.slots.find(s => s.id === eventSlot.id);
	const nextId = Math.max(-1, ...event.slots.map(s => {
		const id = /-(\d+)$/.exec(s.id)?.[1];
		return id ? parseInt(id) : 0;
	})) + 1;
	const start = eventSlot.start.toUTC().toISO({ suppressSeconds: true })!;
	const end = eventSlot.end.toUTC().toISO({ suppressSeconds: true })!;

	// Edit slot in-place if possible
	if (
		oldSlot
		&& oldSlot.id === eventSlot.id
		&& (
			oldSlot.locations.length <= 1
			|| oldSlot.start === start && oldSlot.end === end
		)
	) {
		return {
			...event,
			slots: event.slots.map(s => {
				if (s.id !== oldSlot.id)
					return s;
				const locations = new Set(s.locations);
				locations.delete(eventSlot.origLocation)
				locations.add(eventSlot.location);
				return {
					...s,
					locations: [...locations],
					assigned: eventSlot.assigned.length ? eventSlot.assigned : undefined,
					start,
					end,
				};
			}),
		};
	}

	// Else remove old slot if it exist and insert a new one
	if (oldSlot) {
		event = removeSlotLocation(event, oldSlot, eventSlot.origLocation);
	}

	return {
		...event,
		slots: [...event.slots, {
			id: oldSlot ? oldSlot.id : `${event.id}-${nextId}`,
			locations: [eventSlot.location],
			assigned: eventSlot.assigned.length ? eventSlot.assigned : undefined,
			start,
			end,
		}],
	};
}

const scheduleChanges = computed(() => {
	let eventChanges: ChangeRecord<ScheduleEvent>[] = [];
	for (const change of filterSetOps(changes.value)) {
		if (change.op === "set") {
			let { setEvent, delEvent } = findEvent(change.data, eventChanges, schedule.value);
			if (delEvent && delEvent !== setEvent) {
				eventChanges = removeSlot(eventChanges, delEvent, change.data);
			}
			if (!setEvent) {
				setEvent = {
					id: toId(change.data.name),
					name: change.data.name,
					crew: true,
					slots: [],
				};
			}

			eventChanges = replaceChange({
				op: "set",
				data: mergeSlot(setEvent, change.data),
			}, eventChanges);

		} else if (change.op === "del") {
			let { delEvent } = findEvent(change.data, eventChanges, schedule.value);
			if (delEvent) {
				eventChanges = removeSlot(eventChanges, delEvent, change.data);
			}
		}
	}
	return eventChanges;
});

const schedulePreview = computed(() => {
	const events = [...schedule.value.events]
	applyChangeArray(scheduleChanges.value, events);
	return {
		...schedule.value,
		events,
	};
});

function removeSlot(eventChanges: ChangeRecord<ScheduleEvent>[], event: ScheduleEvent, eventSlot: EventSlot) {
	let oldSlot = event.slots.find(s => s.id === eventSlot.id);
	if (oldSlot) {
		eventChanges = replaceChange({
			op: "set",
			data: removeSlotLocation(event, oldSlot, eventSlot.origLocation),
		}, eventChanges);
	}
	return eventChanges;
}

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

type EventSlotChange = { op: "set" | "del", data: EventSlot } ;

const changes = ref<EventSlotChange[]>([]);
const removed = computed(() => new Set(changes.value.filter(c => c.op === "del").map(c => c.data.id)));

function replaceChange<T extends { op: "set" | "del", data: { id: string  }}>(
	change: T,
	changes: T[],
) {
	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<T extends { op: "set" | "del", data: { id: string }}>(id: string, changes: T[]) {
	return changes.filter(change => change.data.id !== id);
}

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

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

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 newEventName = ref("");
function editEventSlot(
	eventSlot: EventSlot,
	edits: {
		start?: string,
		end?: string,
		duration?: string,
		name?: string,
		location?: string,
		assigned?: number[],
	}
) {
	if (edits.start) {
		const start = DateTime.fromISO(edits.start, { zone: accountStore.activeTimezone, locale: "en-US" });
		eventSlot = {
			...eventSlot,
			start,
			end: start.plus(eventSlot.end.diff(eventSlot.start)),
		};
	}
	if (edits.end !== undefined) {

		eventSlot = {
			...eventSlot,
			end: endFromTime(eventSlot.start, edits.end),
		};
	}
	if (edits.duration !== undefined) {
		eventSlot = {
			...eventSlot,
			end: eventSlot.start.plus(durationFromTime(edits.duration)),
		};
	}
	if (edits.name !== undefined) {
		eventSlot = {
			...eventSlot,
			name: edits.name,
		};
	}
	if (edits.location !== undefined) {
		eventSlot = {
			...eventSlot,
			location: edits.location,
		};
	}
	if (edits.assigned !== undefined) {
		eventSlot = {
			...eventSlot,
			assigned: edits.assigned,
		};
	}
	const change = { op: "set" as const, data: eventSlot };
	changes.value = replaceChange(change, changes.value);
}
function delEventSlot(eventSlot: EventSlot) {
	const change = { op: "del" as const, data: eventSlot };
	changes.value = replaceChange(change, changes.value);
}
function revertEventSlot(id: string) {
	changes.value = revertChange(id, changes.value);
}
function newEventSlot(options: { start?: DateTime, end?: DateTime } = {}) {
	const name = newEventName.value;
	const location = newEventLocation.value;
	if (!location) {
		alert("Invalid location");
		return;
	}
	let start;
	let end;
	const duration = durationFromTime(newEventDuration.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(newEventStart.value, { zone: accountStore.activeTimezone, locale: "en-US" });
		end = endFromTime(start, newEventEnd.value);
	}
	if (!start.isValid || !end.isValid) {
		alert("Invalid start and/or end time");
		return;
	}
	const change: ChangeRecord<EventSlot> = {
		op: "set" as const,
		data: {
			type: "slot",
			id: `$new-${Date.now()}`,
			name,
			origLocation: location,
			location,
			assigned: [],
			start,
			end,
		},
	};
	newEventName.value = "";
	changes.value = replaceChange(change, changes.value);
}
async function saveEventSlots() {
	try {
		await $fetch("/api/schedule", {
			method: "PATCH",
			body: { events: scheduleChanges.value },
		});
		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 eventSlots = computed(() => {
	const data: (EventSlot | Gap)[] = [];
	for (const event of schedule.value.events) {
		for (const slot of event.slots) {
			if (props.eventSlotFilter && !props.eventSlotFilter(slot))
				continue;
			for (const location of slot.locations) {
				if (props.location !== undefined && location !== props.location)
					continue;
				data.push({
					type: "slot",
					id: slot.id,
					event,
					slot,
					name: event.name,
					location,
					assigned: slot.assigned ?? [],
					origLocation: location,
					start: DateTime.fromISO(slot.start, { zone: accountStore.activeTimezone, locale: "en-US" }),
					end: DateTime.fromISO(slot.end, { zone: accountStore.activeTimezone, locale: "en-US" }),
				});
			}
		}
	}
	applyChangeArray(changes.value.filter(change => change.op === "set"), data as EventSlot[]);
	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",
				location: props.location,
				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>
