<template>
	<div class="reports">
		<div class="reports__header">
			<h2>Berichte</h2>
		</div>

		<!-- Error / Success messages -->
		<div v-if="reportsStore.error" class="reports__message reports__message--error">
			{{ reportsStore.error }}
			<NcButton @click="reportsStore.clearError()">
				Schließen
			</NcButton>
		</div>
		<div v-if="reportsStore.success" class="reports__message reports__message--success">
			{{ reportsStore.success }}
			<NcButton @click="reportsStore.clearSuccess()">
				Schließen
			</NcButton>
		</div>

		<!-- Report type selection -->
		<div class="reports__type-grid">
			<div v-for="report in reportsStore.reportTypes"
				:key="report.id"
				class="reports__type-card"
				:class="{
					'reports__type-card--selected': reportsStore.selectedType === report.id,
					'reports__type-card--sensitive': report.sensitive,
				}"
				:title="report.sensitive ? 'Dieser Bericht enthält sensible personenbezogene Daten.' : undefined"
				@click="reportsStore.selectType(report.id)">
				<div class="reports__type-name">
					{{ report.name }}
				</div>
			</div>
		</div>

		<!-- Filter panel (shown when a report is selected) -->
		<div v-if="reportsStore.currentReport" class="reports__filters">
			<h3>Filter</h3>
			<div class="reports__filter-row">
				<!-- Status filter -->
				<div v-if="hasParam('status')" class="reports__filter-item">
					<label for="filter-status">Status:</label>
					<select id="filter-status"
						class="reports__select"
						@change="reportsStore.setFilter('status', $event.target.value || null)">
						<option value="">
							Alle
						</option>
						<option value="aktiv">
							Aktiv
						</option>
						<option value="inaktiv">
							Inaktiv
						</option>
					</select>
				</div>

				<!-- Year filter -->
				<div v-if="hasParam('year')" class="reports__filter-item">
					<label for="filter-year">Jahr:</label>
					<select id="filter-year"
						class="reports__select"
						@change="reportsStore.setFilter('year', $event.target.value)">
						<option v-for="y in yearOptions" :key="y" :value="y">
							{{ y }}
						</option>
					</select>
				</div>

				<!-- Months filter -->
				<div v-if="hasParam('months')" class="reports__filter-item">
					<label for="filter-months">Monate voraus:</label>
					<select id="filter-months"
						class="reports__select"
						@change="reportsStore.setFilter('months', $event.target.value)">
						<option value="1">
							1 Monat
						</option>
						<option value="3" selected>
							3 Monate
						</option>
						<option value="6">
							6 Monate
						</option>
						<option value="12">
							12 Monate
						</option>
					</select>
				</div>

				<!-- Date range filter (for Verletzungsprotokoll) -->
				<div v-if="hasParam('dateFrom')" class="reports__filter-item">
					<label for="filter-date-from">Von:</label>
					<input id="filter-date-from"
						type="date"
						class="reports__select"
						@change="reportsStore.setFilter('dateFrom', $event.target.value || null)">
				</div>
				<div v-if="hasParam('dateTo')" class="reports__filter-item">
					<label for="filter-date-to">Bis:</label>
					<input id="filter-date-to"
						type="date"
						class="reports__select"
						@change="reportsStore.setFilter('dateTo', $event.target.value || null)">
				</div>

				<!-- MemberId filter (for Lagerhistorie / Verletzungsprotokoll) -->
				<div v-if="hasParam('memberId')" class="reports__filter-item">
					<label for="filter-member">Mitglied (ID, leer = alle):</label>
					<input id="filter-member"
						type="number"
						class="reports__select"
						min="1"
						placeholder="Alle"
						@change="reportsStore.setFilter('memberId', $event.target.value || null)">
				</div>

				<!-- Stufe filter -->
				<div v-if="hasParam('stufeId')" class="reports__filter-item">
					<label for="filter-stufe">Stufe:</label>
					<select id="filter-stufe"
						class="reports__select"
						@change="reportsStore.setFilter('stufeId', $event.target.value || null)">
						<option value="">
							Alle Stufen
						</option>
						<option v-for="stufe in stufenStore.stufen"
							:key="stufe.id"
							:value="stufe.id">
							{{ stufe.name }}
						</option>
					</select>
				</div>

				<!-- Preview button -->
				<NcButton type="primary"
					:disabled="reportsStore.previewLoading"
					@click="reportsStore.fetchPreview()">
					{{ reportsStore.previewLoading ? 'Lade...' : 'Vorschau' }}
				</NcButton>
			</div>
		</div>

		<!-- Preview table -->
		<div v-if="reportsStore.previewData" class="reports__preview">
			<div class="reports__preview-header">
				<h3>{{ reportsStore.previewData.title }}</h3>
				<span class="reports__preview-count">
					{{ reportsStore.previewData.rows.length }} Einträge
				</span>
			</div>

			<div class="reports__table-wrapper">
				<table class="reports__table">
					<thead>
						<tr>
							<th v-for="header in reportsStore.previewData.headers" :key="header">
								{{ header }}
							</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(row, idx) in displayRows" :key="idx">
							<td v-for="(cell, cidx) in row" :key="cidx">
								{{ cell }}
							</td>
						</tr>
						<tr v-if="reportsStore.previewData.rows.length > previewLimit">
							<td :colspan="reportsStore.previewData.headers.length"
								class="reports__more-rows">
								... und {{ reportsStore.previewData.rows.length - previewLimit }} weitere Einträge
							</td>
						</tr>
					</tbody>
				</table>
			</div>

			<!-- Download actions -->
			<div class="reports__download-actions">
				<NcButton type="primary"
					:disabled="reportsStore.downloadLoading"
					@click="reportsStore.downloadPdf()">
					PDF herunterladen
				</NcButton>
				<NcButton :disabled="reportsStore.downloadLoading || !hasCsvExport"
					@click="reportsStore.downloadCsv()">
					CSV herunterladen
				</NcButton>
				<NcButton :disabled="reportsStore.downloadLoading"
					@click="showPasswordDialog = true">
					Verschlüsselt herunterladen
				</NcButton>
			</div>
		</div>

		<!-- Password dialog for encrypted export -->
		<div v-if="showPasswordDialog" class="reports__dialog-backdrop">
			<div class="reports__dialog">
				<h3>Verschlüsselter Export</h3>
				<p>
					Der Bericht wird als passwortgeschützte ZIP-Datei (AES-256) heruntergeladen.
				</p>
				<div class="reports__dialog-field">
					<label for="export-password">Passwort (mind. 8 Zeichen):</label>
					<input id="export-password"
						v-model="exportPassword"
						type="password"
						class="reports__input"
						placeholder="Passwort eingeben..."
						@keyup.enter="executeEncryptedDownload">
				</div>
				<div class="reports__dialog-actions">
					<NcButton @click="closePasswordDialog">
						Abbrechen
					</NcButton>
					<NcButton type="primary"
						:disabled="exportPassword.length < 8 || reportsStore.downloadLoading"
						@click="executeEncryptedDownload">
						{{ reportsStore.downloadLoading ? 'Lade...' : 'Herunterladen' }}
					</NcButton>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { NcButton } from '@nextcloud/vue'
import { useReportsStore } from '../stores/reports.js'
import { useStufenStore } from '../stores/stufen.js'

const reportsStore = useReportsStore()
const stufenStore = useStufenStore()

const showPasswordDialog = ref(false)
const exportPassword = ref('')
const previewLimit = 50

// ── Computed ────────────────────────────────────────────────────

const displayRows = computed(() => {
	if (!reportsStore.previewData) return []
	return reportsStore.previewData.rows.slice(0, previewLimit)
})

const yearOptions = computed(() => {
	const current = new Date().getFullYear()
	const years = []
	for (let y = current; y >= current - 5; y--) {
		years.push(y)
	}
	return years
})

const hasCsvExport = computed(() => {
	const csvTypes = ['mitgliederliste', 'beitragsliste', 'geburtstagsliste']
	return csvTypes.includes(reportsStore.selectedType)
})

// ── Methods ─────────────────────────────────────────────────────

function hasParam(name) {
	return reportsStore.currentReport?.params?.includes(name) || false
}

async function executeEncryptedDownload() {
	await reportsStore.downloadEncrypted(exportPassword.value)
	closePasswordDialog()
}

function closePasswordDialog() {
	showPasswordDialog.value = false
	exportPassword.value = ''
}

// ── Lifecycle ───────────────────────────────────────────────────

onMounted(() => {
	reportsStore.fetchReportTypes()
	stufenStore.fetchStufen()
})
</script>

<style scoped>
.reports {
	padding: 20px;
	max-width: 1200px;
}

.reports__header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
}

.reports__header h2 {
	margin: 0;
}

.reports__message {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 12px 16px;
	border-radius: 8px;
	margin-bottom: 16px;
}

.reports__message--error {
	background-color: var(--color-error-hover, #fce4e4);
	color: var(--color-error, #c00);
}

.reports__message--success {
	background-color: var(--color-success-hover, #e4fce4);
	color: var(--color-success, #080);
}

/* ── Report type grid ──────────────────────────────────────────── */

.reports__type-grid {
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
	gap: 12px;
	margin-bottom: 24px;
}

.reports__type-card {
	padding: 16px;
	border: 2px solid var(--color-border, #ddd);
	border-radius: 8px;
	cursor: pointer;
	text-align: center;
	transition: border-color 0.2s, background-color 0.2s;
	position: relative;
}

.reports__type-card:hover {
	border-color: var(--color-primary, #0082c9);
	background-color: var(--color-background-hover, #f5f5f5);
}

.reports__type-card--selected {
	border-color: var(--color-primary, #0082c9);
	background-color: var(--color-primary-element-light, #e0f0ff);
}

.reports__type-name {
	font-weight: 600;
	font-size: 14px;
}

.reports__type-card--sensitive {
	border-color: var(--color-error, #c00);
}

.reports__type-card--sensitive .reports__type-name {
	color: var(--color-error, #c00);
}

.reports__type-card--sensitive:hover {
	border-color: var(--color-error, #c00);
	background-color: color-mix(in srgb, var(--color-error, #c00) 8%, transparent);
}

.reports__type-card--sensitive.reports__type-card--selected {
	border-color: var(--color-error, #c00);
	background-color: color-mix(in srgb, var(--color-error, #c00) 12%, transparent);
}

/* ── Filters ───────────────────────────────────────────────────── */

.reports__filters {
	margin-bottom: 24px;
	padding: 16px;
	background: var(--color-background-dark, #f0f0f0);
	border-radius: 8px;
}

.reports__filters h3 {
	margin: 0 0 12px;
}

.reports__filter-row {
	display: flex;
	flex-wrap: wrap;
	gap: 12px;
	align-items: flex-end;
}

.reports__filter-item {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.reports__filter-item label {
	font-size: 12px;
	font-weight: 600;
	color: var(--color-text-lighter, #666);
}

.reports__select {
	padding: 6px 8px;
	border: 1px solid var(--color-border, #ccc);
	border-radius: 4px;
	min-width: 120px;
}

/* ── Preview table ─────────────────────────────────────────────── */

.reports__preview {
	margin-bottom: 24px;
}

.reports__preview-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12px;
}

.reports__preview-header h3 {
	margin: 0;
}

.reports__preview-count {
	font-size: 13px;
	color: var(--color-text-lighter, #666);
}

.reports__table-wrapper {
	overflow-x: auto;
	margin-bottom: 16px;
}

.reports__table {
	width: 100%;
	border-collapse: collapse;
	font-size: 13px;
}

.reports__table th {
	background: var(--color-primary, #0082c9);
	color: white;
	padding: 8px 12px;
	text-align: left;
	white-space: nowrap;
}

.reports__table td {
	padding: 6px 12px;
	border-bottom: 1px solid var(--color-border, #ddd);
}

.reports__table tr:nth-child(even) {
	background: var(--color-background-dark, #f8f8f8);
}

.reports__table tr:hover {
	background: var(--color-background-hover, #f0f0f0);
}

.reports__more-rows {
	text-align: center;
	font-style: italic;
	color: var(--color-text-lighter, #666);
}

/* ── Download actions ──────────────────────────────────────────── */

.reports__download-actions {
	display: flex;
	gap: 8px;
	flex-wrap: wrap;
}

/* ── Password dialog ───────────────────────────────────────────── */

.reports__dialog-backdrop {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	align-items: center;
	justify-content: center;
	z-index: 1000;
}

.reports__dialog {
	background: var(--color-main-background, #fff);
	padding: 24px;
	border-radius: 12px;
	width: 400px;
	max-width: 90vw;
}

.reports__dialog h3 {
	margin: 0 0 12px;
}

.reports__dialog-field {
	margin: 16px 0;
}

.reports__dialog-field label {
	display: block;
	margin-bottom: 4px;
	font-weight: 600;
}

.reports__input {
	width: 100%;
	padding: 8px;
	border: 1px solid var(--color-border, #ccc);
	border-radius: 4px;
	box-sizing: border-box;
}

.reports__dialog-actions {
	display: flex;
	justify-content: flex-end;
	gap: 8px;
	margin-top: 16px;
}
</style>
