<script setup>
import { computed, inject, ref, useId } from 'vue';

import AlertDialog from '#/components/alerts/create.vue';
import Icon from '#/components/icon/icon.vue';

import StashDialog from '#/components/stashes/create.vue';
import StashMenu from '#/components/stashes/menu.vue';
import { del, get, post } from '#/src/api.js';
import ellipsis from '#/utils/ellipsis.js';

const props = defineProps({
	domain: {
		type: String,
		default: 'scenes',
	},
	item: {
		type: Object,
		default: null,
	},
	showSecondary: {
		type: Boolean,
		default: true,
	},
	showAlert: {
		type: Boolean,
		default: true,
	},
});

const emit = defineEmits(['stashed', 'unstashed']);

const pageContext = inject('pageContext');
const pageStash = pageContext.pageProps.stash;
const user = pageContext.user;

const stashes = ref(pageContext.assets?.stashes);
const primaryStash = pageContext.assets?.primaryStash;
const itemStashes = ref(props.item.stashes);
const itemAlerts = ref(props.item.alerts);
const itemAlerted = ref(props.item.alerts?.only.length > 0);
const hasSecondaryStash = computed(() => itemStashes.value.some((itemStash) => !itemStash.isPrimary));

// console.log(props.item);

const done = ref(true);
const stashMenuDropdownId = useId();
const stashTogglesDropdownId = useId();
const showStashes = ref(false);
const showStashDialog = ref(false);
const showAlertDialog = ref(false);
const feedbackCutoff = 20;

const itemKeys = {
	scenes: 'sceneId',
	actors: 'actorId',
	movies: 'movieId',
};

async function stashItem(stash) {
	if (!done.value) {
		return;
	}

	const stashState = itemStashes.value;

	done.value = false;
	itemStashes.value = itemStashes.value.concat(stash);

	try {
		await post(`/stashes/${stash.id}/${props.domain}`, { [itemKeys[props.domain]]: props.item.id }, {
			successFeedback: `"${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" stashed to ${stash.name}`,
			errorFeedback: `Failed to stash "${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" to ${stash.name}`,
		});

		emit('stashed', stash);
	}
	catch (error) {
		itemStashes.value = stashState;
	}
	finally {
		done.value = true;
	}
}

async function unstashItem(stash) {
	if (!done.value) {
		return;
	}

	const stashState = itemStashes.value;

	done.value = false;
	itemStashes.value = itemStashes.value.filter((itemStash) => itemStash.id !== stash.id);

	try {
		await del(`/stashes/${stash.id}/${props.domain}/${props.item.id}`, {
			undoFeedback: `"${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" unstashed from ${stash.name}`,
			errorFeedback: `Failed to unstash "${ellipsis(props.item.title || props.item.name, feedbackCutoff)}" from ${stash.name}`,
		});

		emit('unstashed', stash);
	}
	catch (error) {
		itemStashes.value = stashState;
	}
	finally {
		done.value = true;
	}
}

async function alertItem() {
	if (!done.value) {
		return;
	}

	const alertLabel = props.item.title || props.item.name;

	done.value = false;
	itemAlerted.value = true;

	try {
		const newAlert = await post('/alerts', {
			...(props.domain === 'actors' && { actors: [props.item.id] }),
			...(props.domain === 'tags' && { tags: [props.item.id] }),
			...(props.domain === 'entities' && { entities: [props.item.id] }),
			...(props.domain === 'scenes' && { scenes: [props.item.id] }),
			notify: true,
			email: false,
			// probably too confusing and annoying to have quick alerts inherit email preference from dialog
			// notify: JSON.parse(localStorage.getItem('alert_notify')) ?? true,
			// email: JSON.parse(localStorage.getItem('alert_email')) ?? false,
			preset: true,
		}, {
			successFeedback: `Alert set for '${alertLabel}'`,
			errorFeedback: `Failed to set alert for '${alertLabel}'`,
			appendErrorMessage: true,
		});

		itemAlerts.value.only = itemAlerts.value.only.concat(newAlert.id);
	}
	catch (error) {
		itemAlerted.value = false;
	}
	finally {
		done.value = true;
	}
}

async function removeAlert() {
	if (done.value === false) {
		return;
	}

	const alertLabel = props.item.title || props.item.name;
	const alertIds = itemAlerts.value.only;

	done.value = false;

	itemAlerted.value = false;
	itemAlerts.value.only = itemAlerts.value.only.filter((alertId) => !alertIds.includes(alertId));

	try {
		await del(`/alerts/${alertIds.join(',')}`, {
			undoFeedback: `Removed alert for '${alertLabel}'`,
			errorFeedback: `Failed to remove alert for '${alertLabel}'`,
			appendErrorMessage: true,
		});
	}
	catch (error) {
		itemAlerted.value = true;
		itemAlerts.value.only = itemAlerts.value.only.concat(alertIds);
	}
	finally {
		done.value = true;
	}
}

function setAlerted(alert) {
	// only set alerted status if the current item is the only one in the new stash
	const items = [...alert.actors, ...alert.tags, ...alert.entities, ...alert.matches, ...alert.scenes];

	if (items.length === 1 && alert[props.domain][0]?.id === props.item.id) {
		itemAlerted.value = true;
		itemAlerts.value.only = itemAlerts.value.only.concat(alert.id);
	}
	else {
		itemAlerts.value.multi = itemAlerts.value.multi.concat(alert.id);
	}
}

function toggleShowStashes(state) {
	if (props.showSecondary) {
		return;
	}

	if (state) {
		showStashes.value = state;
		return;
	}

	showStashes.value = !showStashes.value;
}

async function reloadStashes(newStash) {
	stashes.value = await get(`/users/${user.id}/stashes`);

	await stashItem(newStash);
}
</script>

<template>
	<div
		v-if="user"
		class="bookmarks"
	>
		<div
			v-if="showSecondary && showAlert && !!itemAlerts"
			class="alert-trigger"
		>
			<Icon
				v-if="itemAlerted"
				v-tooltip="`Remove ${itemAlerts.only.length} uncombined alert${itemAlerts.only.length > 1 ? 's' : ''} for '${item.title || item.name}'`"
				icon="bell2"
				class="alert active noselect"
				@click="removeAlert"
			/>

			<Icon
				v-else-if="itemAlerts.multi.length > 0"
				v-tooltip="`Set alert for '${item.title || item.name}', ${itemAlerts.multi.length} combined alert${itemAlerts.multi.length > 1 ? 's' : ''} active`"
				icon="bell-plus"
				class="alert partial noselect"
				@click="alertItem"
			/>

			<Icon
				v-else
				v-tooltip="domain === 'scenes' ? `Set alert for the release of '${item.title}'` : `Set alert for '${item.title || item.name}' releases`"
				icon="bell-plus"
				class="alert noselect"
				@click="alertItem"
				@contextmenu.prevent="showAlertDialog = true"
			/>
		</div>

		<VDropdown
			v-if="itemStashes && (showSecondary || (hasSecondaryStash && pageStash?.user.id !== user.id))"
			:aria-id="stashMenuDropdownId"
			:shown="showStashes"
			placement="auto"
			popper-class="no-outer-scroll"
			@hide="showStashes = false"
		>
			<Icon
				icon="folder-heart"
				class="heart noselect"
				:class="{ favorited: itemStashes.some((itemStash) => !itemStash.isPrimary) }"
				@contextmenu.prevent="showStashes = true"
			/>

			<template #popper>
				<StashMenu
					:stashes="stashes"
					:item-stashes="itemStashes"
					@stash="(stash) => stashItem(stash)"
					@unstash="(stash) => unstashItem(stash)"
					@create="showStashDialog = true"
				/>
			</template>
		</VDropdown>

		<VDropdown
			v-if="itemStashes && (showSecondary || !hasSecondaryStash || pageStash?.user.id === user.id)"
			:aria-id="stashTogglesDropdownId"
			:triggers="[]"
			:shown="showStashes"
			:disabled="showSecondary"
			placement="auto"
			popper-class="no-outer-scroll"
			@hide="showStashes = false"
		>
			<template v-if="pageStash?.user.id === user.id">
				<Icon
					v-if="itemStashes.some((itemStash) => itemStash.id === pageStash.id)"
					:icon="pageStash.isPrimary ? 'heart7' : 'folder-heart'"
					class="heart favorited noselect"
					@click.stop="unstashItem(pageStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>

				<Icon
					v-else
					:icon="pageStash.isPrimary ? 'heart8' : 'folder-heart'"
					class="heart noselect"
					@click.stop="stashItem(pageStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>
			</template>

			<template v-else>
				<Icon
					v-if="itemStashes.some((itemStash) => itemStash.id === primaryStash.id)"
					icon="heart7"
					class="heart favorited noselect"
					@click.stop="unstashItem(primaryStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>

				<Icon
					v-else
					icon="heart8"
					class="heart noselect"
					@click.stop="stashItem(primaryStash)"
					@contextmenu.prevent="toggleShowStashes(true)"
				/>
			</template>

			<template #popper>
				<StashMenu
					:stashes="stashes"
					:item-stashes="itemStashes"
					@stash="(stash) => stashItem(stash)"
					@unstash="(stash) => unstashItem(stash)"
					@create="showStashDialog = true"
				/>
			</template>
		</VDropdown>

		<StashDialog
			v-if="showStashDialog"
			@created="(newStash) => { showStashDialog = false; reloadStashes(newStash); }"
			@close="showStashDialog = false;"
		/>

		<AlertDialog
			v-if="showAlertDialog"
			v-bind="{ [`preset-${domain}`]: [item] }"
			@close="showAlertDialog = false;"
			@alert="(alert) => setAlerted(alert)"
		/>
	</div>
</template>

<style scoped>
.bookmarks {
	display: flex;

	.icon {
		width: 1.5rem;
		height: auto; /* prevents jumping */
		padding: .5rem .5rem;
		fill: var(--glass);
	}

	&.light .icon {
		fill: var(--highlight);
	}

	&.tiled {
		position: absolute;
		top: 0;
		right: 0;

		.icon {
			fill: var(--highlight-strong-20);
			filter: drop-shadow(0 0 3px var(--shadow-strong-10));
		}
	}

	.icon.alert {
		width: 1.3rem;
		padding: .7rem .5rem;
	}

	.icon.heart:hover,
	.icon.alert:hover,
	.icon.heart.favorited,
	.icon.alert.active {
		cursor: pointer;
		fill: var(--primary);
	}

	.icon.alert.partial {
		cursor: pointer;
		fill: var(--text-light);
	}
}

.alert-trigger:not(:last-child) {
	padding-right: .25rem;
	border-right: solid 1px var(--highlight-weak-30);
	margin-right: .25rem;
}
</style>
