<template>
	<div class="family-list">
		<div class="family-list__header">
			<h2>Familien</h2>
			<div class="family-list__actions">
				<NcTextField :model-value="searchQuery"
					:placeholder="'Familien suchen...'"
					:show-trailing-button="searchQuery !== ''"
					trailing-button-icon="close"
					@trailing-button-click="clearSearch"
					@update:model-value="onSearch" />
				<ColumnPicker :columns="allColumns"
					:model-value="visibleKeys"
					@update:model-value="setVisibleKeys" />
				<NcButton type="primary"
					@click="$router.push({ name: 'family-detail', params: { id: 'new' } })">
					<template #icon>
						<Plus :size="20" />
					</template>
					Neue Familie
				</NcButton>
			</div>
		</div>

		<!-- Error state -->
		<NcEmptyContent v-if="store.error && !store.loading"
			name="Fehler"
			:description="store.error">
			<template #icon>
				<AlertCircle :size="64" />
			</template>
			<template #action>
				<NcButton @click="reload">
					Erneut versuchen
				</NcButton>
			</template>
		</NcEmptyContent>

		<!-- Loading state -->
		<NcLoadingIcon v-else-if="store.loading && store.families.length === 0"
			:size="64"
			appearance="dark"
			class="family-list__loading" />

		<!-- Empty state -->
		<NcEmptyContent v-else-if="!store.loading && store.families.length === 0"
			name="Keine Familien"
			:description="searchQuery ? 'Keine Familien für diese Suche gefunden.' : 'Noch keine Familien angelegt.'">
			<template #icon>
				<AccountMultiple :size="64" />
			</template>
			<template #action>
				<NcButton v-if="!searchQuery"
					type="primary"
					@click="$router.push({ name: 'family-detail', params: { id: 'new' } })">
					Erste Familie anlegen
				</NcButton>
			</template>
		</NcEmptyContent>

		<!-- Family table -->
		<table v-else class="family-list__table">
			<thead>
				<tr>
					<th v-for="col in visibleColumns" :key="col.key"
						class="family-list__th"
						:class="{ 'family-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="family in sortedFamilies"
					:key="family.id"
					class="family-list__row"
					@click="$router.push({ name: 'family-detail', params: { id: family.id } })">
					<td v-for="col in visibleColumns" :key="col.key"
						class="family-list__td">
						{{ col.render(family) }}
					</td>
				</tr>
			</tbody>
		</table>

		<!-- Pagination -->
		<PaginationControls
			:current-page="store.currentPage"
			:total-items="store.total"
			:page-size="pageSize"
			item-label="Familien"
			@page="store.goToPage($event)"
			@update:page-size="onPageSizeChange" />
	</div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { NcButton, NcTextField, NcEmptyContent, NcLoadingIcon } from '@nextcloud/vue'
import { useFamiliesStore } from '../stores/families.js'
import { useColumnVisibility } from '../utils/useColumnVisibility.js'
import { usePageSize } from '../utils/usePageSize.js'
import ColumnPicker from '../components/ColumnPicker.vue'
import PaginationControls from '../components/PaginationControls.vue'
import Plus from 'vue-material-design-icons/Plus.vue'
import AlertCircle from 'vue-material-design-icons/AlertCircle.vue'
import AccountMultiple from 'vue-material-design-icons/AccountMultiple.vue'
import SortIcon from '../components/SortIcon.vue'

const store = useFamiliesStore()
const { pageSize, setPageSize } = usePageSize('mv_family_pagesize')
store.limit = pageSize.value

function onPageSizeChange(size) {
	setPageSize(size)
	store.setLimit(size)
}

const searchQuery = ref('')
const sortField = ref('name')
const sortAsc = ref(true)
let searchTimeout = null

function getAnsprechpartner(family) {
	if (!family.members || family.members.length === 0) return '\u2014'
	const contact = family.members.find(m => m.rolle === 'erziehungsberechtigter')
	if (contact) return `${contact.vorname} ${contact.nachname}`
	const first = family.members[0]
	return `${first.vorname} ${first.nachname}`
}

const allColumns = [
	{ key: 'name', label: 'Familienname', sortable: true, sortField: 'name', alwaysVisible: true, render: f => f.name },
	{ key: 'members', label: 'Mitglieder', sortable: true, sortField: '_memberCount', render: f => f.members ? f.members.length : 0 },
	{ key: 'activeChildren', label: 'Aktive Kinder', sortable: true, sortField: '_activeChildren', render: f => f.activeChildrenCount || 0 },
	{ key: 'ansprechpartner', label: 'Ansprechpartner', sortable: true, sortField: '_ansprechpartner', render: f => getAnsprechpartner(f) },
]

const { visibleKeys, visibleColumns, setVisibleKeys } = useColumnVisibility(
	'mv_family_columns',
	allColumns,
	['name', 'members', 'ansprechpartner'],
)

onMounted(() => {
	store.fetchFamilies()
})

const sortedFamilies = computed(() => {
	const families = [...store.families]
	const field = sortField.value
	const asc = sortAsc.value

	return families.sort((a, b) => {
		let valA, valB
		if (field === '_memberCount') {
			valA = a.members ? a.members.length : 0
			valB = b.members ? b.members.length : 0
		} else if (field === '_activeChildren') {
			valA = a.activeChildrenCount || 0
			valB = b.activeChildrenCount || 0
		} else if (field === '_ansprechpartner') {
			valA = getAnsprechpartner(a).toLowerCase()
			valB = getAnsprechpartner(b).toLowerCase()
		} 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
	})
})

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

function onSearch(value) {
	searchQuery.value = value
	clearTimeout(searchTimeout)
	searchTimeout = setTimeout(() => {
		if (value.trim()) {
			store.searchFamilies(value.trim())
		} else {
			store.fetchFamilies()
		}
	}, 300)
}

function clearSearch() {
	searchQuery.value = ''
	store.fetchFamilies()
}

function reload() {
	store.clearError()
	store.fetchFamilies()
}
</script>

<style scoped>
.family-list { padding: 20px; }
.family-list__header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; flex-wrap: wrap; gap: 12px; }
.family-list__header h2 { margin: 0; }
.family-list__actions { display: flex; gap: 12px; align-items: center; }
.family-list__loading { display: flex; justify-content: center; margin-top: 60px; }
.family-list__table { width: 100%; border-collapse: collapse; }
.family-list__th { text-align: left; padding: 12px 16px; border-bottom: 2px solid var(--color-border-dark); font-weight: bold; white-space: nowrap; }
.family-list__th--sortable { cursor: pointer; user-select: none; }
.family-list__th--sortable:hover { background-color: var(--color-background-hover); }
.family-list__row { cursor: pointer; transition: background-color 0.15s ease; }
.family-list__row:hover { background-color: var(--color-background-hover); }
.family-list__td { padding: 10px 16px; border-bottom: 1px solid var(--color-border); }
</style>
