<template>
	<div class="lager-detail">
		<div class="lager-detail__header">
			<NcButton @click="$router.push({ name: 'lager' })">
				Zurück
			</NcButton>
			<h2>{{ camp?.name || 'Lager laden...' }}</h2>
		</div>

		<!-- Messages -->
		<div v-if="lagerStore.error" class="lager-detail__message lager-detail__message--error">
			{{ lagerStore.error }}
			<NcButton @click="lagerStore.clearError()">
				Schließen
			</NcButton>
		</div>
		<div v-if="lagerStore.success" class="lager-detail__message lager-detail__message--success">
			{{ lagerStore.success }}
			<NcButton @click="lagerStore.clearSuccess()">
				Schließen
			</NcButton>
		</div>

		<div v-if="camp" class="lager-detail__content">
			<!-- Camp info -->
			<div class="lager-detail__section">
				<div class="lager-detail__section-header">
					<h3>Details</h3>
					<div v-if="!editing" class="lager-detail__edit-actions">
						<NcButton type="primary" @click="startEditing">
							<template #icon>
								<Pencil :size="20" />
							</template>
							Bearbeiten
						</NcButton>
					</div>
					<div v-else class="lager-detail__edit-actions">
						<NcButton @click="cancelEditing">
							Abbrechen
						</NcButton>
						<NcButton type="primary"
							:disabled="!editForm.name || !editForm.startdatum || !editForm.enddatum"
							@click="saveEditing">
							Speichern
						</NcButton>
					</div>
				</div>
				<div v-if="!editing" class="lager-detail__info-grid">
					<div><strong>Startdatum:</strong> {{ formatDate(camp.startdatum) }}</div>
					<div><strong>Enddatum:</strong> {{ formatDate(camp.enddatum) }}</div>
					<div><strong>Ort:</strong> {{ camp.ort || '-' }}</div>
					<div v-if="camp.beschreibung">
						<strong>Beschreibung:</strong> {{ camp.beschreibung }}
					</div>
				</div>
				<div v-else class="lager-detail__edit-form">
					<label>Name *
						<input v-model="editForm.name" type="text">
					</label>
					<label>Startdatum *
						<input v-model="editForm.startdatum" type="date">
					</label>
					<label>Enddatum *
						<input v-model="editForm.enddatum" type="date">
					</label>
					<label>Ort
						<input v-model="editForm.ort" type="text">
					</label>
					<label>Beschreibung
						<textarea v-model="editForm.beschreibung" rows="3" />
					</label>
				</div>
			</div>

			<!-- Participants -->
			<div class="lager-detail__section">
				<div class="lager-detail__section-header">
					<h3>Teilnehmer ({{ camp.teilnehmer?.length || 0 }})</h3>
					<div class="lager-detail__add-form">
						<NcSelect :model-value="selectedMember"
							:options="memberOptions"
							:reduce="o => o.value"
							label="label"
							placeholder="Mitglied auswählen..."
							:loading="membersLoading"
							:clearable="true"
							class="lager-detail__member-select"
							@update:model-value="selectedMember = $event" />
						<select v-model="newRolle" class="lager-detail__select">
							<option value="Teilnehmer">
								Teilnehmer
							</option>
							<option value="Leitung">
								Leitung
							</option>
						</select>
						<NcButton type="primary"
							:disabled="!selectedMember"
							@click="doAddTeilnehmer">
							Hinzufügen
						</NcButton>
					</div>
				</div>
				<table class="lager-detail__table">
					<thead>
						<tr>
							<th>Name</th>
							<th>Rolle</th>
							<th>Aktion</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="t in camp.teilnehmer" :key="t.memberId">
							<td>{{ t.vorname }} {{ t.nachname }}</td>
							<td>{{ t.rolle }}</td>
							<td>
								<NcButton @click="doRemoveTeilnehmer(t.memberId)">
									Entfernen
								</NcButton>
							</td>
						</tr>
						<tr v-if="!camp.teilnehmer?.length">
							<td colspan="3" class="lager-detail__empty">
								Keine Teilnehmer
							</td>
						</tr>
					</tbody>
				</table>
			</div>

			<!-- Files -->
			<div class="lager-detail__section">
				<h3>Dateien</h3>

				<NcLoadingIcon v-if="folderLoading" :size="32" />

				<div v-else-if="!folderExists" class="lager-detail__folder-missing">
					<p class="lager-detail__empty">
						Der Ordner <strong>{{ folderPath }}</strong> existiert noch nicht.
					</p>
					<NcButton type="primary" @click="createLagerFolder">
						<template #icon>
							<FolderPlus :size="20" />
						</template>
						Ordner erstellen
					</NcButton>
				</div>

				<div v-else>
					<div class="lager-detail__folder-toolbar">
						<span class="lager-detail__folder-path">{{ folderPath }}</span>
						<NcButton @click="openInFiles">
							<template #icon>
								<OpenInNew :size="20" />
							</template>
							In Nextcloud Files öffnen
						</NcButton>
					</div>
					<p v-if="folderFiles.length === 0" class="lager-detail__empty">
						Ordner ist leer
					</p>
					<table v-else class="lager-detail__table">
						<thead>
							<tr>
								<th>Dateiname</th>
								<th>Größe</th>
								<th>Geändert</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="file in folderFiles" :key="file.name">
								<td>{{ file.name }}</td>
								<td>{{ file.type === 'folder' ? '—' : formatSize(file.size) }}</td>
								<td>{{ formatTimestamp(file.mtime) }}</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { NcButton, NcLoadingIcon, NcSelect } from '@nextcloud/vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { useLagerStore } from '../stores/lager.js'
import { formatDate, formatTimestamp } from '../utils/dateFormat.js'
import FolderPlus from 'vue-material-design-icons/FolderPlus.vue'
import OpenInNew from 'vue-material-design-icons/OpenInNew.vue'
import Pencil from 'vue-material-design-icons/Pencil.vue'

const route = useRoute()
const lagerStore = useLagerStore()

const camp = computed(() => lagerStore.currentCamp)

// ── Edit mode ───────────────────────────────────────────────────────
const editing = ref(false)
const editForm = ref({ name: '', startdatum: '', enddatum: '', ort: '', beschreibung: '' })

function startEditing() {
	editForm.value = {
		name: camp.value.name || '',
		startdatum: camp.value.startdatum || '',
		enddatum: camp.value.enddatum || '',
		ort: camp.value.ort || '',
		beschreibung: camp.value.beschreibung || '',
	}
	editing.value = true
}

function cancelEditing() {
	editing.value = false
}

async function saveEditing() {
	try {
		await lagerStore.updateCamp(camp.value.id, editForm.value)
		editing.value = false
	} catch {
		// Error handled by store
	}
}

// ── Participants ────────────────────────────────────────────────────
const selectedMember = ref(null)
const newRolle = ref('Teilnehmer')
const allMembers = ref([])
const membersLoading = ref(false)

async function loadAllMembers() {
	membersLoading.value = true
	try {
		const url = generateUrl('/apps/mitgliederverwaltung/api/v1/members')
		const response = await axios.get(url, { params: { limit: 9999, offset: 0 } })
		allMembers.value = response.data.data || []
	} catch {
		allMembers.value = []
	} finally {
		membersLoading.value = false
	}
}

const memberOptions = computed(() => {
	const existingIds = new Set((camp.value?.teilnehmer || []).map(t => t.memberId))
	return allMembers.value
		.filter(m => !existingIds.has(m.id))
		.map(m => ({
			value: m.id,
			label: `${m.nachname}, ${m.vorname}`,
		}))
})

async function doAddTeilnehmer() {
	if (!selectedMember.value) return
	await lagerStore.addTeilnehmer(camp.value.id, selectedMember.value, newRolle.value)
	selectedMember.value = null
}

async function doRemoveTeilnehmer(memberId) {
	await lagerStore.removeTeilnehmer(camp.value.id, memberId)
}

// ── Files ───────────────────────────────────────────────────────────
const folderLoading = ref(false)
const folderExists = ref(false)
const folderPath = ref('')
const folderFiles = ref([])

async function fetchLagerFiles(lagerId) {
	folderLoading.value = true
	try {
		const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${lagerId}/files/browse`)
		const response = await axios.get(url)
		folderExists.value = response.data.exists || false
		folderPath.value = response.data.path || ''
		folderFiles.value = response.data.files || []
	} catch {
		folderExists.value = false
	} finally {
		folderLoading.value = false
	}
}

async function createLagerFolder() {
	if (!camp.value) return
	folderLoading.value = true
	try {
		const url = generateUrl(`/apps/mitgliederverwaltung/api/v1/lager/${camp.value.id}/files/ensure-folder`)
		const response = await axios.post(url)
		if (response.data.status === 'ok') {
			await fetchLagerFiles(camp.value.id)
		}
	} catch (err) {
		lagerStore.error = err.response?.data?.error || 'Fehler beim Erstellen des Ordners'
	} finally {
		folderLoading.value = false
	}
}

function openInFiles() {
	const url = generateUrl('/apps/files/?dir={dir}', { dir: folderPath.value })
	window.open(url, '_blank')
}

function formatSize(bytes) {
	if (bytes === 0) return '0 B'
	const units = ['B', 'KB', 'MB', 'GB']
	const i = Math.floor(Math.log(bytes) / Math.log(1024))
	const size = (bytes / Math.pow(1024, i)).toFixed(i > 0 ? 1 : 0)
	return size + ' ' + units[i]
}

onMounted(async () => {
	const lagerId = parseInt(route.params.id)
	await lagerStore.fetchCamp(lagerId)
	fetchLagerFiles(lagerId)
	loadAllMembers()
})
</script>

<style scoped>
.lager-detail { padding: 20px; max-width: 1000px; }
.lager-detail__header { display: flex; align-items: center; gap: 16px; margin-bottom: 20px; }
.lager-detail__header h2 { margin: 0; }
.lager-detail__message { padding: 12px; border-radius: 8px; margin-bottom: 16px; display: flex; justify-content: space-between; align-items: center; }
.lager-detail__message--error { background: var(--color-error-hover); color: var(--color-error); }
.lager-detail__message--success { background: var(--color-success-hover, #e8f5e9); color: var(--color-success, #2e7d32); }
.lager-detail__section { margin-bottom: 24px; padding: 16px; background: var(--color-background-dark); border-radius: 8px; }
.lager-detail__section h3 { margin: 0 0 12px; }
.lager-detail__section-header { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 12px; margin-bottom: 12px; }
.lager-detail__section-header h3 { margin: 0; }
.lager-detail__edit-actions { display: flex; gap: 8px; }
.lager-detail__info-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 8px; }
.lager-detail__edit-form { display: flex; flex-direction: column; gap: 12px; }
.lager-detail__edit-form label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; font-size: 13px; }
.lager-detail__edit-form input,
.lager-detail__edit-form textarea { padding: 6px 8px; border: 1px solid var(--color-border); border-radius: 4px; width: 100%; box-sizing: border-box; }
.lager-detail__add-form { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.lager-detail__member-select { min-width: 250px; }
.lager-detail__select { padding: 6px 8px; border: 1px solid var(--color-border); border-radius: 4px; }
.lager-detail__table { width: 100%; border-collapse: collapse; }
.lager-detail__table th { background: var(--color-primary); color: white; padding: 6px 12px; text-align: left; }
.lager-detail__table td { padding: 6px 12px; border-bottom: 1px solid var(--color-border); }
.lager-detail__empty { text-align: center; color: var(--color-text-lighter); padding: 12px; }
.lager-detail__folder-missing { display: flex; flex-direction: column; align-items: center; gap: 12px; padding: 20px; }
.lager-detail__folder-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; }
.lager-detail__folder-path { font-family: monospace; font-size: 0.9em; color: var(--color-text-lighter); }
</style>
