<template>
	<div class="permission-settings">
		<h3>Berechtigungen verwalten</h3>
		<p class="permission-settings__description">
			Weisen Sie Nextcloud-Benutzern Zugriffsrechte zu.
		</p>

		<!-- Error -->
		<div v-if="permStore.error" class="permission-settings__error">
			{{ permStore.error }}
			<NcButton @click="permStore.clearError()">Schließen</NcButton>
		</div>

		<!-- Search/Filter -->
		<div class="permission-settings__filter">
			<NcTextField :model-value="filterQuery"
				placeholder="Benutzer filtern..."
				@update:model-value="filterQuery = $event" />
		</div>

		<!-- Loading -->
		<NcLoadingIcon v-if="permStore.loading && permStore.permissions.length === 0"
			:size="32"
			class="permission-settings__loading" />

		<!-- User list with permissions -->
		<div v-else class="permission-settings__list">
			<div v-for="userPerm in filteredUsers"
				:key="userPerm.uid"
				class="permission-settings__user-row">

				<!-- User info -->
				<div class="permission-settings__user-info">
					<strong>{{ userPerm.displayName || userPerm.uid }}</strong>
					<span class="permission-settings__uid">{{ userPerm.uid }}</span>
				</div>

				<!-- Permission level dropdown -->
				<div class="permission-settings__level">
					<label>Zugriff</label>
					<select :value="userPerm.level"
						class="permission-settings__select"
						@change="onLevelChange(userPerm.uid, $event.target.value)">
						<option value="none">Kein Zugriff</option>
						<option value="read">Lesezugriff</option>
						<option value="stufe">Stufenzugriff</option>
						<option value="full">Vollzugriff</option>
						<option value="admin">Admin</option>
					</select>
				</div>

				<!-- Stufen multi-select (only when level = stufe) -->
				<div v-if="userPerm.level === 'stufe'" class="permission-settings__stufen">
					<label>Erlaubte Stufen</label>
					<div class="permission-settings__stufen-checks">
						<label v-for="stufe in stufen"
							:key="stufe.id"
							class="permission-settings__stufe-check">
							<input type="checkbox"
								:checked="(userPerm.allowedStufen || []).includes(stufe.id)"
								@change="onStufenChange(userPerm.uid, stufe.id, $event.target.checked)">
							<span :style="{ color: stufe.color }">{{ stufe.name }}</span>
						</label>
					</div>
				</div>

				<!-- Banking visibility toggle -->
				<div class="permission-settings__banking">
					<label class="permission-settings__toggle-label">
						<input type="checkbox"
							:checked="userPerm.canSeeBanking"
							@change="onBankingChange(userPerm.uid, $event.target.checked)">
						Bankdaten sichtbar
					</label>
				</div>
			</div>
		</div>

		<!-- No users found -->
		<p v-if="!permStore.loading && filteredUsers.length === 0" class="permission-settings__empty">
			Keine Benutzer gefunden.
		</p>
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { NcButton, NcTextField, NcLoadingIcon } from '@nextcloud/vue'
import { usePermissionsStore } from '../stores/permissions.js'
import { useStufenStore } from '../stores/stufen.js'

const permStore = usePermissionsStore()
const stufenStore = useStufenStore()

const filterQuery = ref('')

const stufen = computed(() => stufenStore.stufen)

/**
 * Merge NC users with their permissions for display.
 */
const filteredUsers = computed(() => {
	const permMap = {}
	for (const perm of permStore.permissions) {
		permMap[perm.ncUserId] = perm
	}

	let users = permStore.users.map(user => ({
		uid: user.uid,
		displayName: user.displayName,
		level: permMap[user.uid]?.level || 'none',
		allowedStufen: permMap[user.uid]?.allowedStufen || [],
		canSeeBanking: permMap[user.uid]?.canSeeBanking || false,
	}))

	// Filter by search query
	if (filterQuery.value.trim()) {
		const q = filterQuery.value.trim().toLowerCase()
		users = users.filter(u =>
			u.uid.toLowerCase().includes(q)
			|| (u.displayName || '').toLowerCase().includes(q),
		)
	}

	return users
})

onMounted(async () => {
	await Promise.all([
		permStore.fetchPermissions(),
		permStore.fetchUsers(),
		stufenStore.fetchStufen(),
	])
})

/**
 * Handle permission level change.
 */
async function onLevelChange(uid, newLevel) {
	const user = filteredUsers.value.find(u => u.uid === uid)
	if (!user) return

	try {
		await permStore.setPermission(
			uid,
			newLevel,
			newLevel === 'stufe' ? user.allowedStufen : null,
			user.canSeeBanking,
		)
	} catch {
		// Error displayed by store
	}
}

/**
 * Handle Stufen checkbox change.
 */
async function onStufenChange(uid, stufeId, checked) {
	const user = filteredUsers.value.find(u => u.uid === uid)
	if (!user) return

	let allowedStufen = [...(user.allowedStufen || [])]
	if (checked) {
		if (!allowedStufen.includes(stufeId)) {
			allowedStufen.push(stufeId)
		}
	} else {
		allowedStufen = allowedStufen.filter(id => id !== stufeId)
	}

	try {
		await permStore.setPermission(
			uid,
			user.level,
			allowedStufen,
			user.canSeeBanking,
		)
	} catch {
		// Error displayed by store
	}
}

/**
 * Handle banking visibility toggle.
 */
async function onBankingChange(uid, canSeeBanking) {
	const user = filteredUsers.value.find(u => u.uid === uid)
	if (!user) return

	try {
		await permStore.setPermission(
			uid,
			user.level,
			user.level === 'stufe' ? user.allowedStufen : null,
			canSeeBanking,
		)
	} catch {
		// Error displayed by store
	}
}
</script>

<style scoped>
.permission-settings__description {
	color: var(--color-text-lighter);
	margin: 0 0 16px 0;
}

.permission-settings__error {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 8px 12px;
	background: var(--color-error);
	color: white;
	border-radius: var(--border-radius);
	margin-bottom: 12px;
}

.permission-settings__filter {
	margin-bottom: 16px;
	max-width: 400px;
}

.permission-settings__loading {
	margin: 20px 0;
}

.permission-settings__list {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.permission-settings__user-row {
	display: flex;
	align-items: center;
	gap: 16px;
	padding: 12px 16px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
	flex-wrap: wrap;
}

.permission-settings__user-info {
	min-width: 200px;
	flex: 1;
}

.permission-settings__uid {
	display: block;
	font-size: 0.85em;
	color: var(--color-text-lighter);
}

.permission-settings__level {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.permission-settings__level label {
	font-size: 0.8em;
	color: var(--color-text-lighter);
}

.permission-settings__select {
	padding: 6px 8px;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	background: var(--color-main-background);
	color: var(--color-text);
}

.permission-settings__stufen {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.permission-settings__stufen > label {
	font-size: 0.8em;
	color: var(--color-text-lighter);
}

.permission-settings__stufen-checks {
	display: flex;
	gap: 12px;
	flex-wrap: wrap;
}

.permission-settings__stufe-check {
	display: flex;
	align-items: center;
	gap: 4px;
	font-size: 0.9em;
	cursor: pointer;
}

.permission-settings__banking {
	display: flex;
	align-items: center;
}

.permission-settings__toggle-label {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 0.9em;
	cursor: pointer;
	white-space: nowrap;
}

.permission-settings__empty {
	color: var(--color-text-lighter);
	font-style: italic;
}
</style>
