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

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

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

		<!-- Content -->
		<div v-else-if="member || isNew" class="member-detail__content">
			<!-- Derived fields banner -->
			<div v-if="!isNew && member" class="member-detail__derived">
				<span v-if="member.geburtsdatum" class="member-detail__derived-item">
					<strong>Alter:</strong> {{ calculateAge(member.geburtsdatum) }} Jahre
				</span>
				<span class="member-detail__derived-item">
					<strong>Mitgliedsdauer:</strong> {{ calculateMembershipDuration(member.eintritt) }}
				</span>
				<span :class="'member-list__status member-list__status--' + member.status">
					{{ formatStatus(member.status) }}
				</span>
			</div>

			<!-- Tabs -->
			<div class="member-detail__tabs">
				<button v-for="tab in tabs"
					:key="tab.id"
					:class="['member-detail__tab', { 'member-detail__tab--active': activeTab === tab.id }]"
					@click="activeTab = tab.id">
					{{ tab.label }}
				</button>
			</div>

			<!-- Tab: Persönlich -->
			<div v-if="activeTab === 'personal'" class="member-detail__tab-content">
				<MemberForm :member="formData"
					:is-new="isNew"
					:editing="editing"
					:errors="validationErrors"
					@update="onFormUpdate" />

				<!-- Sub-entities: Addresses -->
				<div class="member-detail__section">
					<h3>Adressen</h3>
					<SubEntityList :items="formData.addresses || []"
						:fields="addressFields"
						:editing="editing"
						entity-name="Adresse"
						@add="addAddress"
						@update="updateAddressLocal"
						@remove="removeAddress" />
				</div>

				<!-- Sub-entities: Phones -->
				<div class="member-detail__section">
					<h3>Telefonnummern</h3>
					<SubEntityList :items="formData.phones || []"
						:fields="phoneFields"
						:editing="editing"
						entity-name="Telefonnummer"
						@add="addPhone"
						@update="updatePhoneLocal"
						@remove="removePhone" />
				</div>

				<!-- Sub-entities: Emails -->
				<div class="member-detail__section">
					<h3>E-Mail-Adressen</h3>
					<SubEntityList :items="formData.emails || []"
						:fields="emailFields"
						:editing="editing"
						entity-name="E-Mail"
						@add="addEmail"
						@update="updateEmailLocal"
						@remove="removeEmail" />
				</div>

				<!-- Inline save error (shown without replacing the form) -->
				<div v-if="saveError" class="member-detail__save-error">
					<span>{{ saveError }}</span>
					<NcButton @click="saveError = null">Schliessen</NcButton>
				</div>

				<!-- Action buttons -->
				<div class="member-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 || !isFormValid"
							@click="save">
							Speichern
						</NcButton>
						<NcButton @click="cancelEditing">
							Abbrechen
						</NcButton>
					</template>
				</div>
			</div>

			<!-- Tab: Dateien (Files) -->
			<div v-else-if="activeTab === 'files' && !isNew" class="member-detail__tab-content">
				<FileExplorer :member-id="Number(id)" />
			</div>

			<!-- Placeholder tabs -->
			<div v-else class="member-detail__tab-content">
				<NcEmptyContent :name="activeTabLabel"
					description="Wird in einem späteren Milestone implementiert." />
			</div>
		</div>
	</div>
</template>

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

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

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

const activeTab = ref('personal')
const editing = ref(false)
const member = ref(null)
const formData = ref(createEmptyMember())
const saveError = ref(null)

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

const validationErrors = computed(() => {
	const errors = {}
	const d = formData.value
	if (!d.vorname?.trim()) errors.vorname = 'Vorname ist erforderlich'
	if (!d.nachname?.trim()) errors.nachname = 'Nachname ist erforderlich'
	if (!d.eintritt) errors.eintritt = 'Eintrittsdatum ist erforderlich'
	if (!d.rolle) errors.rolle = 'Rolle ist erforderlich'
	return errors
})

const isFormValid = computed(() => Object.keys(validationErrors.value).length === 0)

const tabs = [
	{ id: 'personal', label: 'Persönlich' },
	{ id: 'family', label: 'Familie' },
	{ id: 'fees', label: 'Beitrag' },
	{ id: 'camps', label: 'Lager' },
	{ id: 'injuries', label: 'Verletzungen' },
	{ id: 'files', label: 'Dateien' },
	{ id: 'history', label: 'Verlauf' },
]

const activeTabLabel = computed(() => {
	const tab = tabs.find(t => t.id === activeTab.value)
	return tab ? tab.label : ''
})

// Sub-entity field definitions
const addressFields = [
	{ key: 'label', label: 'Bezeichnung', type: 'text', placeholder: 'z.B. Hauptadresse' },
	{ key: 'strasse', label: 'Straße', type: 'text', required: true },
	{ key: 'plz', label: 'PLZ', type: 'text', required: true },
	{ key: 'ort', label: 'Ort', type: 'text', required: true },
	{ key: 'land', label: 'Land', type: 'text', default: 'Deutschland' },
	{ key: 'isPrimary', label: 'Hauptadresse', type: 'checkbox' },
]

const phoneFields = [
	{ key: 'label', label: 'Bezeichnung', type: 'text', placeholder: 'z.B. Mobil' },
	{ key: 'numberE164', label: 'Nummer (E.164)', type: 'text', required: true, placeholder: '+49...' },
]

const emailFields = [
	{ key: 'label', label: 'Bezeichnung', type: 'text', placeholder: 'z.B. Privat' },
	{ key: 'email', label: 'E-Mail', type: 'text', required: true },
]

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

watch(() => props.id, async () => {
	if (isNew.value) {
		editing.value = true
		formData.value = createEmptyMember()
		member.value = null
	} else {
		await loadMember()
	}
})

async function loadMember() {
	store.clearError()
	try {
		const data = await store.fetchMember(Number(props.id))
		member.value = data
		formData.value = JSON.parse(JSON.stringify(data))
	} catch {
		// Error is handled by the store
	}
}

function todayISO() {
	return new Date().toISOString().split('T')[0]
}

function createEmptyMember() {
	return {
		vorname: '',
		nachname: '',
		geburtsdatum: null,
		geschlecht: null,
		rolle: 'mitglied',
		stufeId: null,
		eintritt: todayISO(),
		austritt: null,
		status: 'aktiv',
		allergienEncrypted: null,
		notizen: null,
		zusatzNotizen: null,
		kvTyp: null,
		kvName: null,
		familyId: null,
		addresses: [],
		phones: [],
		emails: [],
	}
}

function startEditing() {
	formData.value = JSON.parse(JSON.stringify(member.value))
	saveError.value = null
	editing.value = true
}

function cancelEditing() {
	if (isNew.value) {
		router.push({ name: 'members' })
	} else {
		formData.value = JSON.parse(JSON.stringify(member.value))
		editing.value = false
	}
}

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

// Sub-entity local management
function addAddress() {
	formData.value.addresses.push({
		label: null,
		strasse: '',
		plz: '',
		ort: '',
		land: 'Deutschland',
		isPrimary: false,
	})
}

function updateAddressLocal(index, field, value) {
	formData.value.addresses[index][field] = value
}

function removeAddress(index) {
	formData.value.addresses.splice(index, 1)
}

function addPhone() {
	formData.value.phones.push({ label: null, numberE164: '' })
}

function updatePhoneLocal(index, field, value) {
	formData.value.phones[index][field] = value
}

function removePhone(index) {
	formData.value.phones.splice(index, 1)
}

function addEmail() {
	formData.value.emails.push({ label: null, email: '' })
}

function updateEmailLocal(index, field, value) {
	formData.value.emails[index][field] = value
}

function removeEmail(index) {
	formData.value.emails.splice(index, 1)
}

async function save() {
	saveError.value = null
	try {
		if (isNew.value) {
			const created = await store.createMember(formData.value)
			router.push({ name: 'member-detail', params: { id: created.id } })
		} else {
			// Only send editable fields — strip read-only/system fields
			// to avoid polluting the backend validation merge
			const d = formData.value
			const data = {
				vorname: d.vorname,
				nachname: d.nachname,
				geburtsdatum: d.geburtsdatum,
				geschlecht: d.geschlecht,
				rolle: d.rolle,
				stufeId: d.stufeId,
				eintritt: d.eintritt,
				austritt: d.austritt,
				status: d.status,
				allergienEncrypted: d.allergienEncrypted,
				notizen: d.notizen,
				zusatzNotizen: d.zusatzNotizen,
				kvTyp: d.kvTyp,
				kvName: d.kvName,
				familyId: d.familyId,
				frozenFeeRate: d.frozenFeeRate,
				einwilligungDatum: d.einwilligungDatum,
				juleicaNummer: d.juleicaNummer,
				juleicaAblaufdatum: d.juleicaAblaufdatum,
				addresses: d.addresses || [],
				phones: d.phones || [],
				emails: d.emails || [],
			}
			await store.updateMember(Number(props.id), data)
			await loadMember()
			editing.value = false
		}
	} catch (err) {
		saveError.value = err.response?.data?.error || store.error || 'Fehler beim Speichern'
		console.error('Save failed:', err)
	}
}

async function confirmDelete() {
	if (confirm('Mitglied wirklich löschen? Sensible Daten werden unwiderruflich gelöscht.')) {
		try {
			await store.deleteMember(Number(props.id))
			router.push({ name: 'members' })
		} catch {
			// Error displayed from store
		}
	}
}

function calculateAge(geburtsdatum) {
	if (!geburtsdatum) return '—'
	const birth = new Date(geburtsdatum)
	const today = new Date()
	let age = today.getFullYear() - birth.getFullYear()
	const m = today.getMonth() - birth.getMonth()
	if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) age--
	return age
}

function calculateMembershipDuration(eintritt) {
	if (!eintritt) return '—'
	const start = new Date(eintritt)
	const today = new Date()
	let years = today.getFullYear() - start.getFullYear()
	let months = today.getMonth() - start.getMonth()
	if (months < 0) {
		years--
		months += 12
	}
	if (years === 0) return `${months} Monate`
	if (months === 0) return `${years} Jahre`
	return `${years} Jahre, ${months} Monate`
}

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

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

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


.member-detail__header h2 {
	margin: 0;
}

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

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

.member-detail__derived-item {
	font-size: 0.95em;
}

.member-detail__tabs {
	display: flex;
	gap: 0;
	border-bottom: 2px solid var(--color-border-dark);
	margin-bottom: 20px;
}

.member-detail__tab {
	padding: 10px 20px;
	background: none;
	border: none;
	cursor: pointer;
	font-size: 0.95em;
	color: var(--color-text-lighter);
	border-bottom: 2px solid transparent;
	margin-bottom: -2px;
	transition: all 0.15s ease;
}

.member-detail__tab:hover {
	color: var(--color-text);
	background: var(--color-background-hover);
}

.member-detail__tab--active {
	color: var(--color-primary);
	border-bottom-color: var(--color-primary);
	font-weight: 600;
}

.member-detail__tab-content {
	min-height: 300px;
}

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

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

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

/* Reuse status styles from MemberList */
.member-list__status {
	display: inline-block;
	padding: 2px 8px;
	border-radius: var(--border-radius-pill);
	font-size: 0.85em;
	font-weight: 500;
}
.member-list__status--aktiv { background-color: var(--color-success); color: white; }
.member-list__status--inaktiv { background-color: var(--color-warning); color: white; }
.member-list__status--geloescht { background-color: var(--color-error); color: white; }

.member-detail__save-error {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 10px 16px;
	background: var(--color-error);
	color: white;
	border-radius: var(--border-radius-large);
	margin-top: 16px;
}
</style>
