<template>
	<div class="settings">
		<h2>Einstellungen</h2>

		<!-- Stufen Management Section -->
		<div class="settings__section">
			<h3>Stufen verwalten</h3>
			<p class="settings__description">
				Definieren Sie die Stufen Ihrer Gruppe mit Altersbereich und Farbe.
			</p>

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

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

			<!-- Stufen list -->
			<div v-else class="settings__stufen-list">
				<div v-for="(stufe, index) in stufenStore.stufen"
					:key="stufe.id"
					class="settings__stufe-item"
					:style="{ borderLeftColor: stufe.color || 'var(--color-border)' }">

					<div class="settings__stufe-header">
						<!-- Reorder buttons -->
						<div class="settings__stufe-reorder">
							<button :disabled="index === 0"
								class="settings__reorder-btn"
								title="Nach oben"
								@click="moveStufe(index, -1)">
								&#9650;
							</button>
							<button :disabled="index === stufenStore.stufen.length - 1"
								class="settings__reorder-btn"
								title="Nach unten"
								@click="moveStufe(index, 1)">
								&#9660;
							</button>
						</div>

						<!-- Name -->
						<div class="settings__stufe-field settings__stufe-field--name">
							<label>Name</label>
							<NcTextField :model-value="stufe.name"
								@update:model-value="updateStufeField(stufe.id, 'name', $event)" />
						</div>

						<!-- Age range -->
						<div class="settings__stufe-field settings__stufe-field--age">
							<label>Alter von</label>
							<input type="number"
								:value="stufe.ageRangeMin"
								min="0"
								max="99"
								class="settings__number-input"
								@input="updateStufeField(stufe.id, 'ageRangeMin', $event.target.value ? parseInt($event.target.value) : null)">
						</div>
						<div class="settings__stufe-field settings__stufe-field--age">
							<label>Alter bis</label>
							<input type="number"
								:value="stufe.ageRangeMax"
								min="0"
								max="99"
								class="settings__number-input"
								@input="updateStufeField(stufe.id, 'ageRangeMax', $event.target.value ? parseInt($event.target.value) : null)">
						</div>

						<!-- Color -->
						<div class="settings__stufe-field settings__stufe-field--color">
							<label>Farbe</label>
							<input type="color"
								:value="stufe.color || '#808080'"
								class="settings__color-input"
								@input="updateStufeField(stufe.id, 'color', $event.target.value)">
						</div>

						<!-- Member count (read-only info) -->
						<div class="settings__stufe-field settings__stufe-field--count">
							<label>Mitglieder</label>
							<span class="settings__member-count">{{ stufe.memberCount || 0 }}</span>
						</div>

						<!-- Delete button -->
						<NcButton type="error"
							:disabled="(stufe.memberCount || 0) > 0"
							:title="(stufe.memberCount || 0) > 0 ? 'Stufe hat noch zugewiesene Mitglieder' : 'Stufe löschen'"
							@click="confirmDeleteStufe(stufe)">
							Löschen
						</NcButton>
					</div>
				</div>
			</div>

			<!-- Add new Stufe button -->
			<div class="settings__add-stufe">
				<NcButton type="primary" @click="addStufe">
					<template #icon>
						<Plus :size="20" />
					</template>
					Neue Stufe
				</NcButton>
			</div>
		</div>

		<!-- File Integration Section -->
		<div class="settings__section">
			<h3>Datei-Integration</h3>
			<p class="settings__description">
				Konfigurieren Sie, wo Mitglieder- und Lager-Ordner in Nextcloud Files angelegt werden.
			</p>

			<div class="settings__file-fields">
				<div class="settings__file-field">
					<label>Basispfad Mitglieder</label>
					<NcTextField :model-value="filesStore.settings.basePath"
						placeholder="/Verein/Mitglieder/"
						@update:model-value="updateFileSetting('basePath', $event)" />
				</div>

				<div class="settings__file-field">
					<label>Ordner-Muster</label>
					<NcTextField :model-value="filesStore.settings.subfolderPattern"
						placeholder="{Nachname}_{Vorname}"
						@update:model-value="updateFileSetting('subfolderPattern', $event)" />
					<span class="settings__file-hint">Platzhalter: {Vorname}, {Nachname}, {Id}</span>
				</div>

				<div class="settings__file-field">
					<label>Basispfad Lager</label>
					<NcTextField :model-value="filesStore.settings.lagerBasePath"
						placeholder="/Verein/Lager/"
						@update:model-value="updateFileSetting('lagerBasePath', $event)" />
				</div>

				<div class="settings__file-field">
					<label class="settings__toggle-label">
						<input type="checkbox"
							:checked="filesStore.settings.autoCreate"
							@change="updateFileSetting('autoCreate', $event.target.checked)">
						Ordner automatisch erstellen
					</label>
				</div>
			</div>

			<div v-if="fileSaveSuccess" class="settings__file-success">
				Einstellungen gespeichert
			</div>
		</div>

		<!-- Calendar Sync Section -->
		<div class="settings__section">
			<h3>Kalender-Synchronisation</h3>
			<p class="settings__description">
				Synchronisieren Sie Geburtstage und Juleica-Erinnerungen in den Nextcloud-Kalender.
			</p>

			<!-- Error -->
			<div v-if="calendarStore.error" class="settings__error">
				{{ calendarStore.error }}
				<NcButton @click="calendarStore.clearError()">Schliessen</NcButton>
			</div>

			<!-- Success -->
			<div v-if="calendarStore.success" class="settings__calendar-success">
				{{ calendarStore.success }}
				<NcButton @click="calendarStore.clearSuccess()">Schliessen</NcButton>
			</div>

			<!-- Status -->
			<div v-if="calendarStore.status" class="settings__calendar-status">
				<div class="settings__calendar-status-row">
					<span class="settings__calendar-label">Calendar-App:</span>
					<span v-if="calendarStore.status.calendarAppEnabled"
						class="settings__calendar-badge settings__calendar-badge--ok">
						Aktiviert
					</span>
					<span v-else class="settings__calendar-badge settings__calendar-badge--warn">
						Nicht aktiviert
					</span>
					<NcButton v-if="!calendarStore.status.calendarAppEnabled"
						:disabled="calendarStore.enablingApp"
						@click="calendarStore.enableCalendarApp()">
						<NcLoadingIcon v-if="calendarStore.enablingApp" :size="16" />
						<template v-else>Aktivieren</template>
					</NcButton>
				</div>

				<div class="settings__calendar-status-row">
					<span class="settings__calendar-label">Kalender:</span>
					<span v-if="calendarStore.status.calendarExists"
						class="settings__calendar-badge settings__calendar-badge--ok">
						Vorhanden ({{ calendarStore.status.eventCount }} Eintraege)
					</span>
					<span v-else class="settings__calendar-badge settings__calendar-badge--info">
						Wird bei erster Synchronisation erstellt
					</span>
				</div>

				<div class="settings__calendar-status-row">
					<span class="settings__calendar-label">Berechtigte Mitglieder:</span>
					<span>{{ calendarStore.status.eligibleMembers }}</span>
				</div>
			</div>

			<NcLoadingIcon v-else-if="!calendarStore.error" :size="24" class="settings__loading" />

			<!-- Sync button -->
			<div class="settings__calendar-actions">
				<NcButton type="primary"
					:disabled="calendarStore.syncing"
					@click="calendarStore.triggerSync()">
					<NcLoadingIcon v-if="calendarStore.syncing" :size="20" />
					<template v-else>Jetzt synchronisieren</template>
				</NcButton>
			</div>
		</div>

		<!-- Fee Rules Section -->
		<div class="settings__section">
			<FeeRuleEditor />
		</div>

		<!-- Permission Management Section -->
		<div class="settings__section">
			<PermissionSettings />
		</div>
	</div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { NcButton, NcTextField, NcLoadingIcon } from '@nextcloud/vue'
import { useStufenStore } from '../stores/stufen.js'
import { useFilesStore } from '../stores/files.js'
import { useCalendarStore } from '../stores/calendar.js'
import PermissionSettings from '../components/PermissionSettings.vue'
import FeeRuleEditor from '../components/FeeRuleEditor.vue'
import Plus from 'vue-material-design-icons/Plus.vue'

const stufenStore = useStufenStore()
const filesStore = useFilesStore()
const calendarStore = useCalendarStore()

let saveTimeout = null
let fileSaveTimeout = null
const fileSaveSuccess = ref(false)

onMounted(() => {
	stufenStore.fetchStufen()
	filesStore.fetchSettings()
	calendarStore.fetchStatus()
})

/**
 * Update a Stufe field with debounced save.
 */
function updateStufeField(id, field, value) {
	// Update locally first for responsive UI
	const stufe = stufenStore.stufen.find(s => s.id === id)
	if (stufe) {
		stufe[field] = value
	}

	// Debounce the save to avoid too many API calls
	clearTimeout(saveTimeout)
	saveTimeout = setTimeout(async () => {
		try {
			await stufenStore.updateStufe(id, { [field]: value })
		} catch {
			// Error displayed by store
		}
	}, 500)
}

/**
 * Move a Stufe up or down in the list.
 */
async function moveStufe(currentIndex, direction) {
	const newIndex = currentIndex + direction
	if (newIndex < 0 || newIndex >= stufenStore.stufen.length) return

	const orderedIds = stufenStore.stufen.map(s => s.id)
	const [movedId] = orderedIds.splice(currentIndex, 1)
	orderedIds.splice(newIndex, 0, movedId)

	try {
		await stufenStore.reorderStufen(orderedIds)
	} catch {
		// Error displayed by store
	}
}

/**
 * Add a new Stufe with defaults.
 */
async function addStufe() {
	try {
		await stufenStore.createStufe({
			name: 'Neue Stufe',
			sortOrder: stufenStore.stufen.length,
			ageRangeMin: null,
			ageRangeMax: null,
			color: '#808080',
		})
	} catch {
		// Error displayed by store
	}
}

/**
 * Confirm and delete a Stufe.
 */
async function confirmDeleteStufe(stufe) {
	if (confirm(`Stufe "${stufe.name}" wirklich löschen?`)) {
		try {
			await stufenStore.deleteStufe(stufe.id)
		} catch {
			// Error displayed by store (e.g., members still assigned)
		}
	}
}

/**
 * Update a file setting with debounced save.
 */
function updateFileSetting(field, value) {
	filesStore.settings[field] = value
	fileSaveSuccess.value = false

	clearTimeout(fileSaveTimeout)
	fileSaveTimeout = setTimeout(async () => {
		try {
			await filesStore.updateSettings({ [field]: value })
			fileSaveSuccess.value = true
			setTimeout(() => { fileSaveSuccess.value = false }, 2000)
		} catch {
			// Error displayed by store
		}
	}, 500)
}
</script>

<style scoped>
.settings {
	padding: 20px;
	max-width: 1000px;
}

.settings h2 {
	margin: 0 0 24px 0;
}

.settings__section {
	margin-bottom: 32px;
}

.settings__section h3 {
	margin: 0 0 8px 0;
}

.settings__description {
	color: var(--color-text-lighter);
	margin: 0 0 16px 0;
}

.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;
}

.settings__loading {
	margin: 20px 0;
}

.settings__stufen-list {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.settings__stufe-item {
	padding: 12px 16px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
	border-left: 4px solid var(--color-border);
}

.settings__stufe-header {
	display: flex;
	align-items: flex-end;
	gap: 12px;
	flex-wrap: wrap;
}

.settings__stufe-reorder {
	display: flex;
	flex-direction: column;
	gap: 2px;
}

.settings__reorder-btn {
	background: none;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	cursor: pointer;
	padding: 2px 6px;
	font-size: 0.7em;
	color: var(--color-text);
}

.settings__reorder-btn:hover:not(:disabled) {
	background: var(--color-background-hover);
}

.settings__reorder-btn:disabled {
	opacity: 0.3;
	cursor: not-allowed;
}

.settings__stufe-field {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.settings__stufe-field label {
	font-size: 0.8em;
	color: var(--color-text-lighter);
	font-weight: 500;
}

.settings__stufe-field--name {
	flex: 1;
	min-width: 150px;
}

.settings__stufe-field--age {
	width: 80px;
}

.settings__stufe-field--color {
	width: 60px;
}

.settings__stufe-field--count {
	width: 80px;
	text-align: center;
}

.settings__number-input {
	width: 100%;
	padding: 6px 8px;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	background: var(--color-main-background);
	color: var(--color-text);
}

.settings__color-input {
	width: 40px;
	height: 32px;
	padding: 0;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	cursor: pointer;
}

.settings__member-count {
	display: inline-block;
	padding: 6px 0;
	font-weight: 500;
}

.settings__add-stufe {
	margin-top: 16px;
}

.settings__file-fields {
	display: flex;
	flex-direction: column;
	gap: 16px;
	max-width: 500px;
}

.settings__file-field {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.settings__file-field > label {
	font-size: 0.85em;
	color: var(--color-text-lighter);
	font-weight: 500;
}

.settings__file-hint {
	font-size: 0.8em;
	color: var(--color-text-lighter);
}

.settings__file-success {
	margin-top: 8px;
	color: var(--color-success);
	font-size: 0.9em;
}

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

.settings__calendar-status {
	display: flex;
	flex-direction: column;
	gap: 8px;
	padding: 12px 16px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
	margin-bottom: 16px;
}

.settings__calendar-status-row {
	display: flex;
	align-items: center;
	gap: 8px;
}

.settings__calendar-label {
	font-weight: 500;
	min-width: 180px;
}

.settings__calendar-badge {
	display: inline-block;
	padding: 2px 8px;
	border-radius: var(--border-radius-pill);
	font-size: 0.85em;
}

.settings__calendar-badge--ok {
	background: var(--color-success);
	color: white;
}

.settings__calendar-badge--warn {
	background: var(--color-warning);
	color: white;
}

.settings__calendar-badge--info {
	background: var(--color-primary-element-light);
	color: var(--color-primary-element-light-text);
}

.settings__calendar-actions {
	margin-top: 8px;
}
</style>
