<template>
	<div class="page">
		<div
			v-if="interactive"
			class="revs-header"
		>
			<Checkbox
				label="Show finalized"
				:checked="showReviewed"
				@change="(checked) => { showReviewed = checked; reloadRevisions(); }"
			/>
		</div>

		<ul class="revs nolist">
			<li
				v-for="rev in curatedRevisions"
				:key="`rev-${rev.id}`"
				class="rev"
				:class="{ reviewed: reviewedRevisions.has(rev.id) }"
			>
				<div class="rev-header">
					<a
						:href="`/scene/${rev.sceneId}`"
						target="_blank"
						class="rev-link rev-scene nolink noshrink"
					>{{ rev.sceneId }}@{{ rev.hash.slice(0, 6) }}</a>

					<a
						:href="`/scene/${rev.sceneId}`"
						target="_blank"
						class="rev-link rev-title nolink ellipsis"
					>{{ rev.base.title }}</a>

					<div class="rev-details noshrink">
						<a
							v-if="rev.user"
							:href="`/user/${rev.user.username}`"
							target="_blank"
							class="rev-username nolink"
						>{{ rev.user.username }}</a>

						<time
							:datetime="rev.createdAt"
							class="rev-created"
						>{{ format(rev.createdAt, 'yyyy-MM-dd hh:mm') }}</time>
					</div>

					<div class="rev-actions noshrink">
						<span
							v-if="rev.review"
							class="approved"
							:class="{ rejected: !rev.review.isApproved }"
						>{{ rev.review.isApproved ? 'Approved' : 'Rejected' }} by&nbsp;<a
							:href="`/user/${rev.review.username}`"
							target="_blank"
							class="nolink"
						>{{ rev.review.username }}</a>&nbsp;{{ format(rev.review.reviewedAt, 'yyyy-MM-dd hh:mm') }}</span>

						<template v-else-if="interactive">
							<Icon
								v-tooltip="`Ban user from submitting revisions`"
								icon="user-block"
								class="review-reject review-ban"
								@click="banEditor(rev)"
							/>

							<Icon
								v-tooltip="`Reject revision`"
								icon="blocked"
								class="review-reject"
								@click="reviewRevision(rev, false)"
							/>

							<input
								v-model="feedbacks[rev.id]"
								placeholder="Feedback"
								class="input"
							>
						</template>

						<Icon
							v-if="(!rev.review || !rev.review.isApproved) && interactive"
							v-tooltip="`Approve and apply revision`"
							icon="checkmark"
							class="review-approve"
							@click="reviewRevision(rev, true)"
						/>
					</div>
				</div>

				<ul class="rev-deltas">
					<li
						v-for="(delta, index) in rev.deltas"
						:key="`delta-${rev.id}-${index}`"
						class="delta"
					>
						<span class="delta-key ellipsis">{{ delta.key }}</span>

						<div class="delta-deltas">
							<span class="delta-from delta-value">
								<ul
									v-if="Array.isArray(rev.base[delta.key])"
									class="nolist"
								>[
									<li
										v-for="item in rev.base[delta.key]"
										:key="`item-${rev.id}-${index}-${item.id}`"
										class="delta-item"
										:class="{ modified: item.modified }"
									>{{ item.name || item.id || item }}</li>&nbsp;]
								</ul>

								<template v-else-if="rev.base[delta.key] instanceof Date">{{ format(rev.base[delta.key], 'yyyy-MM-dd hh:mm') }}</template>
								<template v-else>{{ rev.base[delta.key] }}</template>
							</span>

							<span class="delta-arrow">⇒</span>

							<span class="delta-to delta-value">
								<ul
									v-if="Array.isArray(delta.value)"
									class="nolist"
								>[
									<li
										v-for="item in delta.value"
										:key="`item-${rev.id}-${index}-${item.id}`"
										class="delta-item"
										:class="{ modified: item.modified }"
									>{{ item.name || item.id || item }}</li>&nbsp;]
								</ul>

								<template v-else-if="delta.value instanceof Date">{{ format(delta.value, 'yyyy-MM-dd hh:mm') }}</template>
								<template v-else>{{ delta.value }}</template>
							</span>
						</div>
					</li>
				</ul>

				<div
					v-if="rev.comment"
					class="rev-comment"
				>
					{{ rev.comment }}
				</div>
			</li>
		</ul>
	</div>
</template>

<script setup>
import { ref, computed, inject } from 'vue';
import { format } from 'date-fns';

import Checkbox from '#/components/form/checkbox.vue';

import { get, post } from '#/src/api.js';

defineProps({
	interactive: {
		type: Boolean,
		default: false,
	},
});

const pageContext = inject('pageContext');
const revisions = ref(pageContext.pageProps.revisions);

const actors = ref(pageContext.pageProps.actors);
const tags = ref(pageContext.pageProps.tags);
const movies = ref(pageContext.pageProps.movies);

const actorsById = computed(() => Object.fromEntries(actors.value.map((actor) => [actor.id, actor])));
const tagsById = computed(() => Object.fromEntries(tags.value.map((tag) => [tag.id, tag])));
const moviesById = computed(() => Object.fromEntries(movies.value.map((movie) => [movie.id, movie])));

const feedbacks = ref({});
const showReviewed = ref(false);
const reviewedRevisions = ref(new Set());

const mappedKeys = {
	actors: actorsById,
	tags: tagsById,
	movies: moviesById,
};

const dateKeys = [
	'date',
	'productionDate',
	'createdAt',
];

const curatedRevisions = computed(() => revisions.value.map((revision) => {
	const curatedBase = Object.fromEntries(Object.entries(revision.base).map(([key, value]) => {
		if (Array.isArray(value) && mappedKeys[key]) {
			return [key, value.map((itemId) => ({
				id: itemId,
				name: mappedKeys[key].value[itemId]?.name || mappedKeys[key].value[itemId]?.title,
				modified: revision.deltas.some((delta) => delta.key === key && !delta.value.some((deltaItemId) => deltaItemId === itemId)),
			}))];
		}

		if (dateKeys.includes(key)) {
			return [key, new Date(value)];
		}

		return [key, value];
	}));

	const curatedDeltas = revision.deltas.map((delta) => {
		if (Array.isArray(delta.value) && mappedKeys[delta.key]) {
			return {
				...delta,
				value: delta.value.map((itemId) => ({
					id: itemId,
					name: mappedKeys[delta.key].value[itemId]?.name || mappedKeys[delta.key].value[itemId]?.title,
					modified: !revision.base[delta.key].includes(itemId),
				})),
			};
		}

		if (dateKeys.includes(delta.key)) {
			return {
				...delta,
				value: new Date(delta.value),
			};
		}

		return delta;
	});

	return {
		...revision,
		base: curatedBase,
		deltas: curatedDeltas,
	};
}));

async function reloadRevisions() {
	const updatedRevisions = await get('/revisions', {
		isFinalized: showReviewed.value ? undefined : false,
		limit: 50,
	});

	actors.value = updatedRevisions.actors;
	tags.value = updatedRevisions.tags;
	movies.value = updatedRevisions.movies;
	revisions.value = updatedRevisions.revisions;
}

async function reviewRevision(revision, isApproved) {
	reviewedRevisions.value.add(revision.id);

	try {
		await post(`/revisions/${revision.id}/reviews`, {
			isApproved,
			feedback: feedbacks.value[revision.id],
		});

		const updatedRevision = await get(`/revisions/${revision.id}`, {
			revisionId: revision.id,
		});

		revisions.value = revisions.value.map((rev) => (rev.id === updatedRevision.revision.id ? updatedRevision.revision : rev));
	} catch (error) {
		reviewedRevisions.value.delete(revision.id);
	}
}

async function banEditor(revision) {
	console.log('ban!', revision);

	await post('/bans', {
		userId: revision.user.id,
		banIp: true,
	});

	await reviewRevision(revision, false);
}
</script>

<style scoped>
.page {
	display: flex;
	flex-direction: column;
	flex-grow: 1;
}

.revs-header {
	display: flex;
	margin-bottom: 1rem;

	.check-container {
		display: inline-flex;
	}
}

.revs {
	width: 100%;
	flex-grow: 1;
	overflow-x: auto;
	padding: 3px; /* prevent shadow from getting cut off */
}

.rev {
	min-width: 1200px;
	display: flex;
	flex-direction: column;
	background: var(--background);
	border-radius: .25rem;
	margin-bottom: .5rem;
	box-shadow: 0 0 3px var(--shadow-weak-30);
	font-size: .9rem;

	&.reviewed {
		pointer-events: none;
		opacity: .5;
	}

	&:hover {
		box-shadow: 0 0 3px var(--primary-light-20);
	}
}

.rev-link {
	color: var(--glass-strong-10);

	&:hover {
		color: var(--primary);
		text-decoration: underline;
	}
}

.rev-header {
	display: flex;
	align-items: stretch;
	border-bottom: solid 1px var(--glass-weak-30);
	overflow: hidden;
}

.rev-scene {
	width: 9rem;
	display: flex;
	box-sizing: border-box;
	padding: .5rem .5rem;
	align-items: center;
}

.rev-title {
	color: inherit;
	padding: .5rem 0;
}

.rev-details {
	display: flex;
	flex-grow: 1;
	justify-content: flex-end;
	gap: 1rem;
	align-items: center;
	margin: 0 1rem;
}

.rev-username {
	font-weight: bold;
}

.rev-actions {
	display: flex;
	align-items: stretch;

	.icon {
		height: 100%;
		padding: 0 1.5rem;
		fill: var(--glass);

		&:hover {
			cursor: pointer;
			fill: var(--text-light);
		}
	}

	.trigger {
		height: 100%;
	}

	.review-approve {
		fill: var(--success);

		&:hover {
			background: var(--success);
		}
	}

	.review-reject {
		fill: var(--error);

		&:hover {
			background: var(--error);
		}
	}

	.review-comment {
		&:hover {
			background: var(--primary);
		}
	}

	.approved {
		display: flex;
		align-items: center;
		color: var(--success);
		padding: .5rem;
	}

	.rejected {
		color: var(--error);
	}
}

.rev-deltas {
	flex-grow: 1;
	padding: 0;
	margin: .25rem 0;
}

.delta {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	padding: .15rem .5rem;

	&:not(:last-child) {
		border-bottom: solid 1px var(--glass-weak-40);
	}
}

.delta-key {
	width: 8.5rem;
	flex-shrink: 0;
}

.delta-deltas {
	display: flex;
	flex-grow: 1;
}

.delta-from {
	width: 40%;
	flex-shrink: 0;
	color: var(--reject);
	padding: .25rem 0;
	margin-right: 1rem;
}

.delta-arrow {
	display: flex;
	align-items: center;
	padding: 0 1rem;
	font-size: 1.2rem;
	color: var(--glass-weak-10);
}

.delta-value {
	display: flex;
	align-items: center;
}

.delta-to {
	flex-grow: 1;
	color: var(--approve);
}

.delta-item {
	line-height: 1.5;

	&:not(:last-child):after {
		content: ',\00a0';
	}

	&.modified {
		font-weight: bold;
	}
}

.rev-comment {
	padding: .5rem .5rem;
	border-top: solid 1px var(--glass-weak-30);
}
</style>
