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

import abbreviateNumber from '#/src/utils/abbreviate-number.js';

const props = defineProps({
	filters: {
		type: Object,
		default: null,
	},
	tags: {
		type: Array,
		default: () => [],
	},
	actorTags: {
		type: Array,
		default: () => [],
	},
});

const emit = defineEmits(['update']);

const { pageProps } = inject('pageContext');

const {
	tag: pageTag,
	actor: pageActor,
} = pageProps;

const search = ref('');
const searchRegexp = computed(() => new RegExp(search.value, 'i'));
const order = ref('priority');
const showActorTags = ref(!!pageActor);
const actorTagsTooltipId = useId();
const allTagsTooltipId = useId();
const sortPriorityTooltipId = useId();
const sortCountTooltipId = useId();
const sortAlphaTooltipId = useId();

const priorityTags = [
	'anal',
	'dp',
	'threesome',
	'gangbang',
	'blowbang',
	'orgy',
	'airtight',
	'dap',
	'dvp',
	'triple-penetration',
	'tap',
	'tvp',
	'transsexual',
	'spitroast',
	'mfm',
	'fmf',
	'bdsm',
	'deepthroat',
	'blowjob',
	'lesbian',
];

const isActorTagsAvailable = computed(() => props.actorTags && (props.filters.actors.length > 0 || pageActor));

const groupedTags = computed(() => {
	// can't show actor tags inside stash, because both require a join, and manticore currently only supports one
	const tags = showActorTags.value && isActorTagsAvailable.value
		? props.actorTags
		: props.tags;

	const selected = tags.filter((tag) => props.filters.tags.includes(tag.slug));
	const filtered = tags.filter((tag) => !props.filters.tags.includes(tag.slug)
		&& tag.id !== pageTag?.id
		&& searchRegexp.value.test(tag.name));

	if (order.value === 'count') {
		const available = filtered.sort((tagA, tagB) => {
			if (order.value === 'count') {
				return tagB.count - tagA.count;
			}

			return 0;
		});

		return {
			// page: [pageTag],
			selected,
			available,
		};
	}

	if (order.value === 'priority') {
		return {
			// page: [pageTag],
			selected,
			available: [
				...priorityTags.map((priorityTag) => filtered.find((tag) => tag.slug === priorityTag)).filter(Boolean),
				...filtered.filter((tag) => !priorityTags.includes(tag.slug)),
			],
		};
	}

	return {
		// page: [pageTag],
		selected,
		available: filtered,
	};
});

function toggleTag(tag, combine) {
	emit('update', 'onlyActorTags', showActorTags.value, false);

	if (props.filters.tags.includes(tag.slug)) {
		emit('update', 'tags', props.filters.tags.filter((tagId) => tagId !== tag.slug));
		return;
	}

	if (combine) {
		emit('update', 'tags', props.filters.tags.concat(tag.slug));
	}
	else {
		emit('update', 'tags', [tag.slug]);
	}
}
</script>

<template>
	<div class="filter tags-container">
		<div class="filters-sort">
			<label class="filter-search">
				<input
					v-model="search"
					type="search"
					:placeholder="`Filter ${groupedTags.available.length} tags`"
					class="input input-inline filters-search"
				>

				<Icon icon="search" />
			</label>

			<template v-if="isActorTagsAvailable">
				<div
					v-show="showActorTags"
					v-tooltip="{ content: 'Tags relevant to the selected actors', ariaId: actorTagsTooltipId }"
					class="filter-sort order noselect"
					@click="showActorTags = false"
				>
					<Icon icon="user-tags" />
				</div>

				<div
					v-show="!showActorTags"
					v-tooltip="{ content: 'All tags', ariaId: allTagsTooltipId }"
					class="filter-sort order noselect"
					@click="showActorTags = true"
				>
					<Icon icon="price-tags" />
				</div>
			</template>

			<div
				v-show="order === 'priority'"
				v-tooltip="{ content: 'Sorted by tag priority', ariaId: sortPriorityTooltipId }"
				class="filter-sort order noselect"
				@click="order = 'count'"
			>
				<Icon icon="star" />
			</div>

			<div
				v-show="order === 'count'"
				v-tooltip="{ content: 'Sorted by number of scenes', ariaId: sortCountTooltipId }"
				class="filter-sort order noselect"
				@click="order = 'name'"
			>
				<Icon
					icon="sort-numeric-desc"
				/>
			</div>

			<div
				v-show="order === 'name'"
				v-tooltip="{ content: 'Sorted alphanumerically', ariaId: sortAlphaTooltipId }"
				class="filter-sort order noselect"
				@click="order = 'priority'"
			>
				<Icon
					icon="sort-alpha-asc"
				/>
			</div>
		</div>

		<div
			v-if="groupedTags.available.length === 0 && groupedTags.selected.length === 0"
			class="filter-empty"
		>No tags</div>

		<template v-else>
			<ul
				v-for="(group, groupKey) in groupedTags"
				:key="groupKey"
				class="filter-items nolist"
				:class="groupKey"
			>
				<li
					v-for="(tag, index) in group"
					:key="`filter-tag-${tag.id}`"
					class="filter-item"
					:class="{
						selected: filters.tags.includes(tag.slug),
						first: groupKey === 'available' && index === 0 && filters.tags.length > 0,
						disabled: groupKey === 'page',
					}"
					@click.stop="toggleTag(tag, false)"
				>
					<div
						class="filter-include"
						@click.stop="toggleTag(tag, true)"
					>
						<Icon
							icon="checkmark"
							class="filter-add"
						/>

						<Icon
							icon="cross2"
							class="filter-remove"
						/>
					</div>

					<span class="filter-name tag-name">
						<span
							class="filter-text"
							:title="tag.name"
						>{{ tag.name }}</span>

						<span class="tag-details">
							<span
								v-if="tag.count"
								:title="tag.count"
								class="filter-count"
							>{{ abbreviateNumber(tag.count) }}</span>
						</span>
					</span>
				</li>
			</ul>
		</template>
	</div>
</template>

<style scoped>
.filter-items {
	max-height: 15rem;
	overflow-y: auto;
}

.filter {
	padding: 0;
}
</style>
