<template>
	<div class="lager-list">
		<div class="lager-list__header">
			<h2>Lager</h2>
			<div class="lager-list__actions">
				<div class="lager-list__filters">
					<select class="lager-list__select"
						@change="onYearChange($event.target.value)">
						<option value="">
							Alle Jahre
						</option>
						<option v-for="year in lagerStore.availableYears"
							:key="year"
							:value="year">
							{{ year }}
						</option>
					</select>
					<select class="lager-list__select"
						@change="onStufeChange($event.target.value)">
						<option value="">
							Alle Stufen
						</option>
						<option v-for="stufe in stufenStore.stufen"
							:key="stufe.id"
							:value="stufe.id">
							{{ stufe.name }}
						</option>
					</select>
				</div>
				<ColumnPicker :columns="allColumns"
					:model-value="visibleKeys"
					@update:model-value="setVisibleKeys" />
				<NcButton type="primary" @click="showCreate = true">
					Neues Lager
				</NcButton>
			</div>
		</div>

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

		<!-- Camp list -->
		<div v-if="lagerStore.loading" class="lager-list__loading">
			Lade Lager...
		</div>
		<table v-else class="lager-list__table">
			<thead>
				<tr>
					<th v-for="col in visibleColumns" :key="col.key"
						class="lager-list__th"
						:class="{ 'lager-list__th--sortable': col.sortable }"
						@click="col.sortable && toggleSort(col.sortField || col.key)">
						{{ col.label }}
						<SortIcon v-if="col.sortable"
							:field="col.sortField || col.key"
							:current-sort="sortField"
							:sort-asc="sortAsc" />
					</th>
				</tr>
			</thead>
			<tbody>
				<tr v-for="camp in paginatedItems"
					:key="camp.id"
					class="lager-list__row"
					@click="$router.push({ name: 'lager-detail', params: { id: camp.id } })">
					<td v-for="col in visibleColumns" :key="col.key">
						<template v-if="col.key === 'aktionen'">
							<NcButton @click.stop="confirmDelete(camp)">
								Löschen
							</NcButton>
						</template>
						<template v-else>{{ col.render(camp) }}</template>
					</td>
				</tr>
				<tr v-if="lagerStore.camps.length === 0">
					<td :colspan="visibleColumns.length" class="lager-list__empty">
						Keine Lager gefunden
					</td>
				</tr>
			</tbody>
		</table>

		<!-- Pagination -->
		<PaginationControls
			:current-page="currentPage"
			:total-items="totalItems"
			:page-size="pageSize"
			item-label="Lager"
			@page="goToPage"
			@update:page-size="onPageSizeChange" />

		<!-- Create dialog -->
		<div v-if="showCreate" class="lager-list__dialog-backdrop">
			<div class="lager-list__dialog">
				<h3>Neues Lager erstellen</h3>
				<div class="lager-list__form">
					<label>Name *
						<input v-model="newCamp.name" type="text">
					</label>
					<label>Startdatum *
						<input v-model="newCamp.startdatum" type="date">
					</label>
					<label>Enddatum *
						<input v-model="newCamp.enddatum" type="date">
					</label>
					<label>Ort
						<input v-model="newCamp.ort" type="text">
					</label>
					<label>Beschreibung
						<textarea v-model="newCamp.beschreibung" rows="3" />
					</label>
				</div>
				<div class="lager-list__dialog-actions">
					<NcButton @click="showCreate = false">
						Abbrechen
					</NcButton>
					<NcButton type="primary"
						:disabled="!newCamp.name || !newCamp.startdatum || !newCamp.enddatum"
						@click="doCreate">
						Erstellen
					</NcButton>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { NcButton } from '@nextcloud/vue'
import { useLagerStore } from '../stores/lager.js'
import { useStufenStore } from '../stores/stufen.js'
import { useColumnVisibility } from '../utils/useColumnVisibility.js'
import { usePageSize } from '../utils/usePageSize.js'
import { useClientPagination } from '../utils/useClientPagination.js'
import ColumnPicker from '../components/ColumnPicker.vue'
import PaginationControls from '../components/PaginationControls.vue'
import SortIcon from '../components/SortIcon.vue'
import { formatDate } from '../utils/dateFormat.js'

const lagerStore = useLagerStore()
const stufenStore = useStufenStore()
const { pageSize, setPageSize } = usePageSize('mv_lager_pagesize')

const showCreate = ref(false)
const newCamp = ref({ name: '', startdatum: '', enddatum: '', ort: '', beschreibung: '' })
const sortField = ref('startdatum')
const sortAsc = ref(false)

const allColumns = [
	{ key: 'name', label: 'Name', sortable: true, sortField: 'name', alwaysVisible: true, render: c => c.name },
	{ key: 'startdatum', label: 'Startdatum', sortable: true, sortField: 'startdatum', render: c => formatDate(c.startdatum) },
	{ key: 'enddatum', label: 'Enddatum', sortable: true, sortField: 'enddatum', render: c => formatDate(c.enddatum) },
	{ key: 'ort', label: 'Ort', sortable: true, sortField: 'ort', render: c => c.ort || '-' },
	{ key: 'beschreibung', label: 'Beschreibung', render: c => c.beschreibung ? (c.beschreibung.length > 50 ? c.beschreibung.substring(0, 50) + '\u2026' : c.beschreibung) : '\u2014' },
	{ key: 'teilnehmer', label: 'Teilnehmer', sortable: true, sortField: '_teilnehmerCount', render: c => c.teilnehmer?.length || 0 },
	{ key: 'aktionen', label: 'Aktionen', render: () => '' },
]

const { visibleKeys, visibleColumns, setVisibleKeys } = useColumnVisibility(
	'mv_lager_columns',
	allColumns,
	['name', 'startdatum', 'enddatum', 'ort', 'teilnehmer', 'aktionen'],
)

const sortedCamps = computed(() => {
	const camps = [...lagerStore.camps]
	const field = sortField.value
	const asc = sortAsc.value

	return camps.sort((a, b) => {
		let valA, valB
		if (field === '_teilnehmerCount') {
			valA = a.teilnehmer?.length || 0
			valB = b.teilnehmer?.length || 0
		} else {
			valA = a[field] ?? ''
			valB = b[field] ?? ''
		}

		if (typeof valA === 'string') {
			valA = valA.toLowerCase()
			valB = String(valB).toLowerCase()
		}

		if (valA < valB) return asc ? -1 : 1
		if (valA > valB) return asc ? 1 : -1
		return 0
	})
})

const { currentPage, totalItems, paginatedItems, goToPage, resetPage } = useClientPagination(sortedCamps, pageSize)

function onPageSizeChange(size) {
	setPageSize(size)
	resetPage()
}

function toggleSort(field) {
	if (sortField.value === field) {
		sortAsc.value = !sortAsc.value
	} else {
		sortField.value = field
		sortAsc.value = true
	}
}

function onYearChange(val) {
	lagerStore.filterYear = val ? parseInt(val) : null
	lagerStore.fetchCamps()
}

function onStufeChange(val) {
	lagerStore.filterStufeId = val ? parseInt(val) : null
	lagerStore.fetchCamps()
}

async function doCreate() {
	try {
		await lagerStore.createCamp(newCamp.value)
		showCreate.value = false
		newCamp.value = { name: '', startdatum: '', enddatum: '', ort: '', beschreibung: '' }
	} catch {
		// Error handled by store
	}
}

async function confirmDelete(camp) {
	if (confirm(`Lager "${camp.name}" wirklich löschen?`)) {
		await lagerStore.deleteCamp(camp.id)
	}
}

onMounted(() => {
	lagerStore.fetchCamps()
	stufenStore.fetchStufen()
})
</script>

<style scoped>
.lager-list { padding: 20px; max-width: 1200px; }
.lager-list__header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 12px; }
.lager-list__header h2 { margin: 0; }
.lager-list__actions { display: flex; gap: 12px; align-items: center; }
.lager-list__filters { display: flex; gap: 8px; }
.lager-list__select { padding: 6px 8px; border: 1px solid var(--color-border); border-radius: 4px; }
.lager-list__message { padding: 12px; border-radius: 8px; margin-bottom: 16px; display: flex; justify-content: space-between; }
.lager-list__message--error { background: var(--color-error-hover, #fce4e4); color: var(--color-error); }
.lager-list__loading { padding: 40px; text-align: center; color: var(--color-text-lighter); }
.lager-list__table { width: 100%; border-collapse: collapse; font-size: 14px; }
.lager-list__th { background: var(--color-primary); color: white; padding: 8px 12px; text-align: left; white-space: nowrap; }
.lager-list__th--sortable { cursor: pointer; user-select: none; }
.lager-list__th--sortable:hover { background-color: var(--color-primary-element-hover); }
.lager-list__table td { padding: 8px 12px; border-bottom: 1px solid var(--color-border); }
.lager-list__row { cursor: pointer; }
.lager-list__row:hover { background: var(--color-background-hover); }
.lager-list__empty { text-align: center; padding: 40px; color: var(--color-text-lighter); }
.lager-list__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; }
.lager-list__dialog { background: var(--color-main-background); padding: 24px; border-radius: 12px; width: 480px; max-width: 90vw; }
.lager-list__form { display: flex; flex-direction: column; gap: 12px; margin: 16px 0; }
.lager-list__form label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; font-size: 13px; }
.lager-list__form input, .lager-list__form textarea { padding: 6px 8px; border: 1px solid var(--color-border); border-radius: 4px; width: 100%; box-sizing: border-box; }
.lager-list__dialog-actions { display: flex; justify-content: flex-end; gap: 8px; }
</style>
