<script setup lang="ts">
import {
	ArrowLeftRightIcon,
	BoxIcon,
	ExternalIcon,
	FileIcon,
	GlassesIcon,
	PaintbrushIcon,
	SearchIcon,
	SpinnerIcon,
} from '@modrinth/assets'
import Fuse from 'fuse.js'
import { computed, nextTick, ref, watchSyncEffect } from 'vue'

import Avatar from '#ui/components/base/Avatar.vue'
import BulletDivider from '#ui/components/base/BulletDivider.vue'
import type { OverflowMenuOption } from '#ui/components/base/buttons'
import { ButtonLink } from '#ui/components/base/buttons'
import Checkbox from '#ui/components/base/Checkbox.vue'
import FilterPills from '#ui/components/base/FilterPills.vue'
import StyledInput from '#ui/components/base/StyledInput.vue'
import NewModal from '#ui/components/modal/NewModal.vue'
import { defineMessages, useVIntl } from '#ui/composables/i18n'
import { injectPageContext } from '#ui/providers/page-context'
import {
	commonMessages,
	commonProjectTypeCategoryMessages,
	commonProjectTypeTitleMessages,
	normalizeProjectType,
} from '#ui/utils/common-messages'

import { getClientWarningType } from '../../composables/content-filtering'
import type { ContentCardProject, ContentCardTableItem, ContentItem } from '../../types'
import ContentCardTable from '../ContentCardTable.vue'
import ContentSelectionBar from '../ContentSelectionBar.vue'

const { formatMessage } = useVIntl()
const pageContext = injectPageContext(null)

interface Props {
	header?: string
	sourceName?: string
	sourceIconUrl?: string
	enableToggle?: boolean
	actionDisabled?: boolean
	actionDisabledTooltip?: string | null
	getOverflowOptions?: (item: ContentItem) => OverflowMenuOption[]
	switchVersion?: (item: ContentItem) => void
	showEnvironmentWarnings?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	header: undefined,
	sourceName: undefined,
	sourceIconUrl: undefined,
	enableToggle: false,
	actionDisabled: false,
	actionDisabledTooltip: undefined,
	getOverflowOptions: undefined,
	switchVersion: undefined,
	showEnvironmentWarnings: false,
})

const emit = defineEmits<{
	'update:enabled': [item: ContentItem, value: boolean]
	'bulk:enable': [items: ContentItem[]]
	'bulk:disable': [items: ContentItem[]]
	hide: []
}>()

const messages = defineMessages({
	header: {
		id: 'instances.managed-content-modal.header',
		defaultMessage: 'Managed content',
	},
	searchPlaceholder: {
		id: 'instances.managed-content-modal.search-placeholder',
		defaultMessage: 'Search {count, number} {count, plural, one {project} other {projects}}',
	},
	loading: {
		id: 'instances.managed-content-modal.loading',
		defaultMessage: 'Loading content...',
	},
	emptyTitle: {
		id: 'instances.managed-content-modal.empty-title',
		defaultMessage: 'No content found',
	},
	emptyDescription: {
		id: 'instances.managed-content-modal.empty-description',
		defaultMessage: 'This source does not include any managed content.',
	},
	noResults: {
		id: 'instances.managed-content-modal.no-results',
		defaultMessage: 'No projects match your search.',
	},
	externalContent: {
		id: 'instances.managed-content-modal.external-content',
		defaultMessage: 'External',
	},
	externalContentDescription: {
		id: 'instances.managed-content-modal.external-content-description',
		defaultMessage: 'This file is not published on Modrinth.',
	},
	openInSlicer: {
		id: 'instances.managed-content-modal.open-in-slicer',
		defaultMessage: 'Open in Slicer',
	},
	downloadFile: {
		id: 'instances.managed-content-modal.download-file',
		defaultMessage: 'Download File',
	},
})

export interface ManagedContentModalState {
	items: ContentItem[]
	searchQuery: string
	selectedFilters: string[]
	scrollTop: number
}

const modal = ref<InstanceType<typeof NewModal>>()
const scrollContainer = ref<HTMLElement | null>(null)
const isOpen = ref(false)
const items = ref<ContentItem[]>([])
const disabledIds = ref(new Set<string>())
const loading = ref(false)
const searchQuery = ref('')
const selectedFilters = ref<string[]>([])
const selectedIds = ref<string[]>([])

const selectedItems = computed(() =>
	items.value.filter((item) => selectedIds.value.includes(item.id)),
)
const toggleableSelectedItems = computed(() => selectedItems.value)

const allSelected = computed(() => {
	if (filteredItems.value.length === 0) return false
	return filteredItems.value.every((item) => selectedIds.value.includes(item.id))
})

const someSelected = computed(() => {
	return (
		filteredItems.value.some((item) => selectedIds.value.includes(item.id)) && !allSelected.value
	)
})

function toggleSelectAll() {
	if (allSelected.value || someSelected.value) {
		selectedIds.value = []
	} else {
		selectedIds.value = filteredItems.value.map((item) => item.id)
	}
}

const fuse = new Fuse<ContentItem>([], {
	keys: ['project.title', 'owner.name', 'file_name'],
	threshold: 0.4,
	distance: 100,
})

watchSyncEffect(() => fuse.setCollection(items.value))

const filterOptions = computed(() => {
	const frequency = items.value.reduce(
		(map, item) => {
			const normalized = normalizeProjectType(item.project_type)
			map[normalized] = (map[normalized] || 0) + 1
			return map
		},
		{} as Record<string, number>,
	)

	const options = Object.entries(frequency)
		.sort(([, a], [, b]) => b - a)
		.map(([type]) => {
			const msg =
				commonProjectTypeCategoryMessages[type as keyof typeof commonProjectTypeCategoryMessages]
			return {
				id: type,
				label: msg ? formatMessage(msg) : type.charAt(0).toUpperCase() + type.slice(1) + 's',
			}
		})

	if (
		items.value.some((item) => getClientWarningType(item, props.showEnvironmentWarnings) !== null)
	) {
		options.push({ id: 'warnings', label: 'Warnings' })
	}

	if (props.enableToggle && items.value.some((item) => item.enabled === false)) {
		options.push({ id: 'disabled', label: 'Disabled' })
	}

	return options
})

const stats = computed(() => {
	const counts: Record<string, number> = {}
	for (const item of items.value) {
		const normalized = normalizeProjectType(item.project_type)
		counts[normalized] = (counts[normalized] || 0) + 1
	}
	return counts
})

const attributeFilterIds = new Set(['disabled', 'warnings'])

const typeFilteredCount = computed(() => {
	if (selectedFilters.value.length === 0) return items.value.length
	const typeFilters = selectedFilters.value.filter((f) => !attributeFilterIds.has(f))
	const hasDisabledFilter = props.enableToggle && selectedFilters.value.includes('disabled')
	const hasWarningsFilter = selectedFilters.value.includes('warnings')
	return items.value.filter((item) => {
		if (typeFilters.length > 0 && !typeFilters.includes(normalizeProjectType(item.project_type)))
			return false
		if (hasDisabledFilter && item.enabled) return false
		if (hasWarningsFilter && getClientWarningType(item, props.showEnvironmentWarnings) === null)
			return false
		return true
	}).length
})

const filteredItems = computed(() => {
	const query = searchQuery.value.trim()

	let result: ContentItem[]
	if (query) {
		result = fuse.search(query).map(({ item }) => item)
	} else {
		result = sortContentItems(items.value)
	}

	if (selectedFilters.value.length > 0) {
		const typeFilters = selectedFilters.value.filter((f) => !attributeFilterIds.has(f))
		const hasDisabledFilter = props.enableToggle && selectedFilters.value.includes('disabled')
		const hasWarningsFilter = selectedFilters.value.includes('warnings')
		result = result.filter((item) => {
			if (typeFilters.length > 0 && !typeFilters.includes(normalizeProjectType(item.project_type)))
				return false
			if (hasDisabledFilter && item.enabled) return false
			if (hasWarningsFilter && getClientWarningType(item, props.showEnvironmentWarnings) === null)
				return false
			return true
		})
	}

	return sortContentItems(result, !query)
})

function contentVersionLabel(item: ContentItem): string {
	if (item.embedded_metadata?.version) return item.embedded_metadata.version
	return formatMessage(commonMessages.unknownLabel)
}

const tableItems = computed<ContentCardTableItem[]>(() =>
	filteredItems.value.map((item) => ({
		id: item.id,
		project: item.project ?? {
			id: item.id,
			slug: null,
			title: item.embedded_metadata?.name ?? item.file_name,
			icon_url: item.embedded_metadata?.icon_url ?? null,
		},
		projectLink: !item.external && item.project?.id ? `/project/${item.project.id}` : undefined,
		version: item.version ?? {
			id: item.id,
			version_number: contentVersionLabel(item),
			file_name: item.file_name,
		},
		owner: item.owner
			? {
					...item.owner,
					link:
						item.owner.type === 'user'
							? `/user/${encodeURIComponent(item.owner.id)}`
							: `https://modrinth.com/organization/${item.owner.id}`,
				}
			: undefined,
		source: item.source
			? {
					...item.source,
					link: item.source.link ?? sourceProjectLink(item.source.project),
				}
			: undefined,
		...(props.enableToggle ? { enabled: item.enabled } : {}),
		locked: item.locked,
		installing: item.installing === true,
		toggleDisabled: props.actionDisabled,
		toggleDisabledTooltip: props.actionDisabled ? props.actionDisabledTooltip : undefined,
		isClientOnly: getClientWarningType(item, props.showEnvironmentWarnings) !== null,
		clientWarning: getClientWarningType(item, props.showEnvironmentWarnings),
		disabled:
			props.actionDisabled || disabledIds.value.has(item.file_name) || item.installing === true,
		disabledTooltip: props.actionDisabled ? props.actionDisabledTooltip : undefined,
		overflowOptions: [
			...(props.switchVersion && !item.locked
				? [
						{
							id: 'switch-version',
							label: formatMessage(commonMessages.switchVersionButton),
							icon: ArrowLeftRightIcon,
							action: () => props.switchVersion!(item),
						},
					]
				: []),
			...(props.getOverflowOptions?.(item) ?? []),
		],
	})),
)
const externalItemIds = computed(
	() => new Set(items.value.filter((item) => item.external && !item.source).map((item) => item.id)),
)
const externalSlicerUrls = computed(() => {
	const urls: Record<string, string> = {}
	for (const item of items.value) {
		if (item.external && item.external_url) {
			urls[item.id] = `https://slicer.run/?url=${encodeURIComponent(item.external_url)}`
		}
	}
	return urls
})
const externalUrls = computed(() => {
	const urls: Record<string, string> = {}
	for (const item of items.value) {
		if (item.external && item.external_url) {
			urls[item.id] = item.external_url
		}
	}
	return urls
})
const hasExternalSlicerUrls = computed(() => Object.keys(externalSlicerUrls.value).length > 0)
const showTableActions = computed(() => props.enableToggle || hasExternalSlicerUrls.value)

function getTypeIcon(type: string) {
	switch (type) {
		case 'mod':
			return BoxIcon
		case 'shaderpack':
		case 'shader':
			return GlassesIcon
		case 'resourcepack':
			return PaintbrushIcon
		default:
			return BoxIcon
	}
}

function sortContentItems(contentItems: ContentItem[], sortByName = true) {
	return [...contentItems].sort((a, b) => {
		const externalDiff = Number(b.external === true) - Number(a.external === true)
		if (externalDiff !== 0) return externalDiff
		if (!sortByName) return 0

		return itemDisplayName(a).toLowerCase().localeCompare(itemDisplayName(b).toLowerCase())
	})
}

function itemDisplayName(item: ContentItem) {
	return item.project?.title ?? item.file_name
}

function sourceProjectLink(project: ContentCardProject) {
	const projectId = project.slug ?? project.id
	const url = `https://modrinth.com/modpack/${encodeURIComponent(projectId)}`
	return pageContext ? () => pageContext.openExternalUrl(url) : url
}

function handleEnabledChange(id: string, value: boolean) {
	if (props.actionDisabled) return
	const item = items.value.find((item) => item.id === id)
	if (!item) return
	emit('update:enabled', item, value)
}

function bulkEnable() {
	if (props.actionDisabled) return
	emit('bulk:enable', [...toggleableSelectedItems.value])
	selectedIds.value = []
}

function bulkDisable() {
	if (props.actionDisabled) return
	emit('bulk:disable', [...toggleableSelectedItems.value])
	selectedIds.value = []
}

function show(contentItems: ContentItem[]) {
	items.value = contentItems.map((item) => ({ ...item }))
	searchQuery.value = ''
	selectedFilters.value = []
	selectedIds.value = []
	disabledIds.value = new Set()
	loading.value = false
	showModal()
}

function showLoading() {
	items.value = []
	searchQuery.value = ''
	selectedFilters.value = []
	selectedIds.value = []
	loading.value = true
	showModal()
}

function showModal() {
	if (isOpen.value || !modal.value) return
	isOpen.value = true
	modal.value.show()
}

function hide() {
	isOpen.value = false
	modal.value?.hide()
}

function handleHide() {
	isOpen.value = false
	emit('hide')
}

function getState(): ManagedContentModalState | null {
	if (!items.value.length) return null
	return {
		items: items.value,
		searchQuery: searchQuery.value,
		selectedFilters: [...selectedFilters.value],
		scrollTop: scrollContainer.value?.scrollTop ?? 0,
	}
}

async function restore(state: ManagedContentModalState) {
	items.value = state.items.map((item) => ({ ...item }))
	searchQuery.value = state.searchQuery
	selectedFilters.value = state.selectedFilters
	loading.value = false
	showModal()
	await nextTick()
	if (scrollContainer.value) {
		scrollContainer.value.scrollTop = state.scrollTop
	}
}

function updateItem(fileName: string, updates: Partial<ContentItem> & { disabled?: boolean }) {
	if (updates.disabled !== undefined) {
		const newSet = new Set(disabledIds.value)
		if (updates.disabled) {
			newSet.add(fileName)
		} else {
			newSet.delete(fileName)
		}
		disabledIds.value = newSet
	}
	const { disabled: _, ...itemUpdates } = updates
	if (Object.keys(itemUpdates).length > 0) {
		items.value = items.value.map((item) =>
			item.file_name === fileName ? { ...item, ...itemUpdates } : item,
		)
	}
}

function setItems(contentItems: ContentItem[]) {
	const contentIds = new Set(contentItems.map((item) => item.id))
	const contentFileNames = new Set(contentItems.map((item) => item.file_name))
	items.value = contentItems.map((item) => ({ ...item }))
	selectedIds.value = selectedIds.value.filter((id) => contentIds.has(id))
	disabledIds.value = new Set([...disabledIds.value].filter((id) => contentFileNames.has(id)))
	loading.value = false
}

defineExpose({ show, showLoading, hide, getState, restore, updateItem, setItems })
</script>

<template>
	<NewModal
		ref="modal"
		:max-width="'min(928px, calc(95vw - 10rem))'"
		:width="'min(928px, calc(95vw - 10rem))'"
		:on-hide="handleHide"
		no-padding
	>
		<template #title>
			<Avatar
				v-if="props.sourceIconUrl"
				:src="props.sourceIconUrl"
				:alt="props.sourceName"
				size="3rem"
				:tint-by="props.sourceName"
			/>
			<span class="text-lg font-extrabold text-contrast">
				{{ props.header ?? formatMessage(messages.header) }}
			</span>
		</template>
		<div class="flex flex-col h-[min(600px,calc(95vh-10rem))]">
			<div class="flex flex-col gap-4 px-6 py-4 border-b border-solid border-0 border-surface-4">
				<StyledInput
					v-model="searchQuery"
					:icon="SearchIcon"
					:placeholder="formatMessage(messages.searchPlaceholder, { count: typeFilteredCount })"
					clearable
				/>

				<FilterPills
					v-if="filterOptions.length > 0"
					v-model="selectedFilters"
					:options="filterOptions"
				>
					<template #all>
						{{ formatMessage(commonMessages.allProjectType) }}
					</template>
				</FilterPills>
			</div>

			<div class="flex-1 flex flex-col min-h-0 overflow-hidden">
				<div
					v-if="loading"
					class="flex flex-col items-center justify-center flex-1 gap-2 text-secondary"
				>
					<SpinnerIcon class="size-8 animate-spin" />
					<span class="text-sm">{{ formatMessage(messages.loading) }}</span>
				</div>

				<div
					v-else-if="items.length === 0"
					class="flex flex-col items-center justify-center flex-1 gap-2 text-center p-8"
				>
					<span class="text-xl font-semibold text-contrast">
						{{ formatMessage(messages.emptyTitle) }}
					</span>
					<span class="text-secondary">{{ formatMessage(messages.emptyDescription) }}</span>
				</div>

				<div
					v-else-if="filteredItems.length === 0"
					class="flex flex-col items-center justify-center flex-1 gap-2 text-center p-8"
				>
					<span class="text-secondary">{{ formatMessage(messages.noResults) }}</span>
				</div>

				<div v-else class="@container flex-1 min-h-0 flex flex-col">
					<div
						class="flex h-12 shrink-0 items-center justify-between gap-4 border-0 border-b border-solid border-surface-4 bg-surface-3 px-3"
					>
						<div
							class="flex min-w-0 items-center gap-4"
							:class="
								showTableActions
									? 'flex-1 @[800px]:w-[45%] @[800px]:shrink-0 @[800px]:flex-none'
									: 'flex-1'
							"
						>
							<Checkbox
								v-if="props.enableToggle"
								:model-value="allSelected"
								:indeterminate="someSelected"
								:aria-label="formatMessage(commonMessages.selectAllLabel)"
								class="shrink-0"
								@update:model-value="toggleSelectAll"
							/>
							<span class="font-semibold text-secondary">{{
								formatMessage(commonMessages.projectLabel)
							}}</span>
						</div>
						<div
							class="hidden @[800px]:flex"
							:class="showTableActions ? 'flex-1 min-w-0' : 'flex-1'"
						>
							<span class="font-semibold text-secondary">{{
								formatMessage(commonMessages.versionLabel)
							}}</span>
						</div>
						<div v-if="showTableActions" class="min-w-[160px] shrink-0 text-right">
							<span class="font-semibold text-secondary">{{
								formatMessage(commonMessages.actionsLabel)
							}}</span>
						</div>
					</div>
					<div ref="scrollContainer" class="flex-1 min-h-0 overflow-y-auto">
						<ContentCardTable
							v-model:selected-ids="selectedIds"
							:items="tableItems"
							:show-selection="props.enableToggle"
							:show-item-actions="hasExternalSlicerUrls"
							hide-delete
							hide-header
							flat
							v-on="
								props.enableToggle
									? { 'update:enabled': (id: string, val: boolean) => handleEnabledChange(id, val) }
									: {}
							"
						>
							<template #itemTitleBadges="{ item }">
								<span
									v-if="externalItemIds.has(item.id)"
									v-tooltip="formatMessage(messages.externalContentDescription)"
									class="inline-flex shrink-0 items-center rounded-full border border-solid border-orange bg-orange-highlight px-2 py-0.5 text-xs font-semibold leading-4 text-orange"
								>
									{{ formatMessage(messages.externalContent) }}
								</span>
							</template>
							<template #itemButtonsRight="{ item }">
								<ButtonLink
									v-if="externalSlicerUrls[item.id]"
									v-tooltip="formatMessage(messages.openInSlicer)"
									type="quiet"
									:aria-label="formatMessage(messages.openInSlicer)"
									:href="externalSlicerUrls[item.id]"
									target="_blank"
									rel="noopener noreferrer"
									class="!w-9 !px-0 !rounded-full"
								>
									<ExternalIcon class="size-4" />
								</ButtonLink>
								<ButtonLink
									v-if="externalUrls[item.id]"
									v-tooltip="formatMessage(messages.downloadFile)"
									type="quiet"
									:aria-label="formatMessage(messages.downloadFile)"
									:href="externalUrls[item.id]"
									target="_blank"
									rel="noopener noreferrer"
									class="!w-9 !px-0 !rounded-full"
								>
									<FileIcon class="size-4" />
								</ButtonLink>
							</template>
						</ContentCardTable>
					</div>
				</div>
			</div>

			<div
				class="flex items-center justify-between px-6 py-4 border-t border-solid border-0 border-surface-4 shrink-0"
			>
				<div class="flex items-center gap-2">
					<template v-for="(count, type, idx) in stats" :key="type">
						<BulletDivider v-if="idx > 0" />
						<div class="flex items-center gap-1.5">
							<component :is="getTypeIcon(type as string)" class="size-5 text-secondary" />
							<span class="font-medium text-primary">
								{{ count }}
								{{
									formatMessage(
										commonProjectTypeTitleMessages[
											normalizeProjectType(
												type as string,
											) as keyof typeof commonProjectTypeTitleMessages
										] ?? commonProjectTypeTitleMessages.project,
										{ count },
									)
								}}
							</span>
						</div>
					</template>
				</div>
			</div>
		</div>

		<ContentSelectionBar
			v-if="props.enableToggle"
			:selected-items="selectedItems"
			:toggle-items="toggleableSelectedItems"
			:is-busy="props.actionDisabled"
			:busy-tooltip="props.actionDisabledTooltip"
			:hide-when-modal-open="false"
			style="--left-bar-width: 0px; --right-bar-width: 0px"
			@clear="selectedIds = []"
			@enable="bulkEnable"
			@disable="bulkDisable"
		/>
	</NewModal>
</template>
