<template>
	<div class="family-detail">
		<!-- Header with back button and title -->
		<div class="family-detail__header">
			<NcButton @click="$router.push({ name: 'families' })">
				<template #icon>
					<ArrowLeft :size="20" />
				</template>
				Zurück
			</NcButton>
			<h2 v-if="isNew">Neue Familie</h2>
			<h2 v-else-if="family">{{ family.name }}</h2>
		</div>

		<!-- Loading -->
		<NcLoadingIcon v-if="store.loading && !family"
			:size="64"
			class="family-detail__loading" />

		<!-- Error -->
		<NcEmptyContent v-else-if="store.error"
			name="Fehler"
			:description="store.error">
			<template #action>
				<NcButton @click="loadFamily">Erneut versuchen</NcButton>
			</template>
		</NcEmptyContent>

		<!-- Content -->
		<div v-else-if="family || isNew" class="family-detail__content">
			<!-- Info banner -->
			<div v-if="!isNew && family" class="family-detail__info">
				<span class="family-detail__info-item">
					<strong>Mitglieder:</strong> {{ family.members ? family.members.length : 0 }}
				</span>
				<span class="family-detail__info-item">
					<strong>Aktive Kinder:</strong> {{ family.activeChildrenCount || 0 }}
				</span>
			</div>

			<!-- Family form -->
			<FamilyForm :family="formData"
				:editing="editing"
				@update="onFormUpdate" />

			<!-- Linked members section -->
			<div v-if="!isNew" class="family-detail__section">
				<h3>Verknüpfte Mitglieder</h3>

				<!-- Members list -->
				<div v-if="formData.members && formData.members.length > 0" class="family-detail__members">
					<div v-for="member in formData.members"
						:key="member.id"
						class="family-detail__member-row">
						<span class="family-detail__member-name"
							@click="$router.push({ name: 'member-detail', params: { id: member.id } })">
							{{ member.nachname }}, {{ member.vorname }}
						</span>
						<span :class="'family-detail__role family-detail__role--' + member.rolle">
							{{ formatRolle(member.rolle) }}
						</span>
						<span :class="'family-detail__status family-detail__status--' + member.status">
							{{ formatStatus(member.status) }}
						</span>
						<NcButton v-if="editing"
							type="error"
							@click="removeMember(member.id)">
							Entfernen
						</NcButton>
					</div>
				</div>
				<p v-else class="family-detail__no-members">Keine Mitglieder verknüpft.</p>

				<!-- Add member -->
				<div v-if="editing" class="family-detail__add-member">
					<NcTextField :model-value="memberSearchQuery"
						placeholder="Mitglied suchen (Name eingeben)..."
						@update:model-value="onMemberSearch" />
					<div v-if="memberSearchResults.length > 0" class="family-detail__search-results">
						<div v-for="result in memberSearchResults"
							:key="result.id"
							class="family-detail__search-result"
							@click="addMember(result.id)">
							{{ result.nachname }}, {{ result.vorname }}
							<span v-if="result.familyId" class="family-detail__already-linked">
								(bereits in Familie)
							</span>
						</div>
					</div>
				</div>
			</div>

			<!-- Action buttons -->
			<div class="family-detail__actions">
				<template v-if="!editing">
					<NcButton type="primary" @click="startEditing">
						Bearbeiten
					</NcButton>
					<NcButton v-if="!isNew"
						type="error"
						@click="confirmDelete">
						Löschen
					</NcButton>
				</template>
				<template v-else>
					<NcButton type="primary"
						:disabled="store.loading"
						@click="save">
						Speichern
					</NcButton>
					<NcButton @click="cancelEditing">
						Abbrechen
					</NcButton>
				</template>
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { NcButton, NcEmptyContent, NcLoadingIcon, NcTextField } from '@nextcloud/vue'
import { useFamiliesStore } from '../stores/families.js'
import { useMembersStore } from '../stores/members.js'
import FamilyForm from '../components/FamilyForm.vue'
import ArrowLeft from 'vue-material-design-icons/ArrowLeft.vue'

const props = defineProps({
	id: {
		type: [String, Number],
		required: true,
	},
})

const router = useRouter()
const store = useFamiliesStore()
const membersStore = useMembersStore()

const editing = ref(false)
const family = ref(null)
const formData = ref(createEmptyFamily())
const memberSearchQuery = ref('')
const memberSearchResults = ref([])
let memberSearchTimeout = null

const isNew = computed(() => props.id === 'new')

onMounted(async () => {
	if (isNew.value) {
		editing.value = true
		formData.value = createEmptyFamily()
	} else {
		await loadFamily()
	}
})

watch(() => props.id, async () => {
	if (isNew.value) {
		editing.value = true
		formData.value = createEmptyFamily()
		family.value = null
	} else {
		await loadFamily()
	}
})

function createEmptyFamily() {
	return {
		name: '',
		kontoinhaberEncrypted: null,
		ibanEncrypted: null,
		bic: null,
		kreditinstitut: null,
		members: [],
	}
}

async function loadFamily() {
	try {
		const data = await store.fetchFamily(Number(props.id))
		family.value = data
		formData.value = JSON.parse(JSON.stringify(data))
	} catch {
		// Error handled by store
	}
}

function startEditing() {
	formData.value = JSON.parse(JSON.stringify(family.value))
	editing.value = true
}

function cancelEditing() {
	if (isNew.value) {
		router.push({ name: 'families' })
	} else {
		formData.value = JSON.parse(JSON.stringify(family.value))
		editing.value = false
	}
	memberSearchQuery.value = ''
	memberSearchResults.value = []
}

function onFormUpdate(field, value) {
	formData.value[field] = value
}

async function save() {
	try {
		if (isNew.value) {
			const data = { ...formData.value }
			delete data.members
			const created = await store.createFamily(data)
			router.push({ name: 'family-detail', params: { id: created.id } })
		} else {
			const data = { ...formData.value }
			delete data.members
			delete data.id
			delete data.activeChildrenCount
			delete data.createdAt
			delete data.updatedAt
			await store.updateFamily(Number(props.id), data)
			await loadFamily()
			editing.value = false
		}
		memberSearchQuery.value = ''
		memberSearchResults.value = []
	} catch (err) {
		console.error('Save failed:', err)
	}
}

async function confirmDelete() {
	if (confirm('Familie wirklich löschen? Mitglieder werden nicht gelöscht, nur die Verknüpfung wird aufgehoben.')) {
		try {
			await store.deleteFamily(Number(props.id))
			router.push({ name: 'families' })
		} catch {
			// Error displayed by store
		}
	}
}

/**
 * Search for members to link.
 */
function onMemberSearch(value) {
	memberSearchQuery.value = value
	clearTimeout(memberSearchTimeout)

	if (!value || value.trim().length < 2) {
		memberSearchResults.value = []
		return
	}

	memberSearchTimeout = setTimeout(async () => {
		try {
			await membersStore.searchMembers(value.trim())
			// Filter out already-linked members
			const linkedIds = (formData.value.members || []).map(m => m.id)
			memberSearchResults.value = membersStore.members.filter(m => !linkedIds.includes(m.id))
		} catch {
			memberSearchResults.value = []
		}
	}, 300)
}

async function addMember(memberId) {
	try {
		await store.linkMember(Number(props.id), memberId)
		family.value = store.currentFamily
		formData.value = JSON.parse(JSON.stringify(store.currentFamily))
		memberSearchQuery.value = ''
		memberSearchResults.value = []
	} catch {
		// Error displayed by store
	}
}

async function removeMember(memberId) {
	try {
		await store.unlinkMember(Number(props.id), memberId)
		family.value = store.currentFamily
		formData.value = JSON.parse(JSON.stringify(store.currentFamily))
	} catch {
		// Error displayed by store
	}
}

function formatRolle(rolle) {
	const map = {
		mitglied: 'Kind',
		erziehungsberechtigter: 'Erziehungsberechtigter',
	}
	return map[rolle] || rolle
}

function formatStatus(status) {
	const map = { aktiv: 'Aktiv', inaktiv: 'Inaktiv', geloescht: 'Gelöscht' }
	return map[status] || status
}
</script>

<style scoped>
.family-detail {
	padding: 20px;
	max-width: 900px;
}

.family-detail__header {
	display: flex;
	align-items: center;
	gap: 16px;
	margin-bottom: 20px;
}

.family-detail__header h2 {
	margin: 0;
}

.family-detail__loading {
	display: flex;
	justify-content: center;
	margin-top: 60px;
}

.family-detail__info {
	display: flex;
	gap: 24px;
	padding: 12px 16px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius-large);
	margin-bottom: 20px;
}

.family-detail__info-item {
	font-size: 0.95em;
}

.family-detail__section {
	margin-top: 24px;
	padding-top: 16px;
	border-top: 1px solid var(--color-border);
}

.family-detail__section h3 {
	margin: 0 0 12px 0;
}

.family-detail__members {
	display: flex;
	flex-direction: column;
	gap: 8px;
}

.family-detail__member-row {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 8px 12px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
}

.family-detail__member-name {
	flex: 1;
	cursor: pointer;
	color: var(--color-primary);
}

.family-detail__member-name:hover {
	text-decoration: underline;
}

.family-detail__role {
	font-size: 0.85em;
	padding: 2px 8px;
	border-radius: var(--border-radius-pill);
	background: var(--color-background-darker);
}

.family-detail__role--erziehungsberechtigter {
	background: var(--color-primary-element-light);
	color: var(--color-primary-element-light-text);
}

.family-detail__status {
	font-size: 0.85em;
	padding: 2px 8px;
	border-radius: var(--border-radius-pill);
}

.family-detail__status--aktiv {
	background-color: var(--color-success);
	color: white;
}

.family-detail__status--inaktiv {
	background-color: var(--color-warning);
	color: white;
}

.family-detail__no-members {
	color: var(--color-text-lighter);
	font-style: italic;
}

.family-detail__add-member {
	margin-top: 12px;
	position: relative;
}

.family-detail__search-results {
	position: absolute;
	top: 100%;
	left: 0;
	right: 0;
	background: var(--color-main-background);
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
	max-height: 200px;
	overflow-y: auto;
	z-index: 100;
}

.family-detail__search-result {
	padding: 8px 12px;
	cursor: pointer;
	transition: background-color 0.15s ease;
}

.family-detail__search-result:hover {
	background-color: var(--color-background-hover);
}

.family-detail__already-linked {
	color: var(--color-text-lighter);
	font-size: 0.85em;
}

.family-detail__actions {
	display: flex;
	gap: 12px;
	margin-top: 24px;
	padding-top: 16px;
	border-top: 1px solid var(--color-border);
	flex-wrap: wrap;
}
</style>
