<template>
	<div class="family-form">
		<div class="family-form__row">
			<label class="family-form__label">Familienname *</label>
			<NcTextField :model-value="family.name"
				:disabled="!editing"
				placeholder="z.B. Mueller"
				@update:model-value="$emit('update', 'name', $event)" />
		</div>

		<div v-if="editing" class="family-form__row">
			<label class="family-form__label">Oder aus Mitgliedern wählen</label>
			<div class="family-form__member-picker">
				<NcSelect :model-value="selectedMember"
					:options="filteredMemberOptions"
					:reduce="o => o.value"
					label="label"
					placeholder="Mitglied auswählen..."
					:loading="membersLoading"
					:clearable="true"
					@update:model-value="onMemberSelected" />
				<label class="family-form__filter-label">
					<input v-model="hideAlreadyInFamily"
						type="checkbox"
						class="family-form__checkbox">
					Nur Mitglieder ohne Familie anzeigen
				</label>
			</div>
		</div>

		<!-- Banking section (only visible with banking permission) -->
		<div class="family-form__section">
			<h4>Bankverbindung</h4>

			<div class="family-form__row">
				<label class="family-form__label">Kontoinhaber</label>
				<NcTextField :model-value="family.kontoinhaberEncrypted || ''"
					:disabled="!editing"
					placeholder="Name des Kontoinhabers"
					@update:model-value="$emit('update', 'kontoinhaberEncrypted', $event)" />
			</div>

			<div class="family-form__row">
				<label class="family-form__label">IBAN</label>
				<div class="family-form__iban-wrapper">
					<NcTextField :model-value="family.ibanEncrypted || ''"
						:disabled="!editing"
						placeholder="DE89 3704 0044 0532 0130 00"
						@update:model-value="onIbanInput" />
					<span v-if="ibanValidation !== null" :class="ibanValidationClass">
						{{ ibanValidation }}
					</span>
				</div>
			</div>

			<div class="family-form__row">
				<label class="family-form__label">BIC</label>
				<NcTextField :model-value="family.bic || ''"
					:disabled="!editing"
					placeholder="COBADEFFXXX"
					@update:model-value="$emit('update', 'bic', $event)" />
			</div>

			<div class="family-form__row">
				<label class="family-form__label">Kreditinstitut</label>
				<NcTextField :model-value="family.kreditinstitut || ''"
					:disabled="!editing"
					placeholder="Name der Bank"
					@update:model-value="$emit('update', 'kreditinstitut', $event)" />
			</div>
		</div>
	</div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { NcTextField, NcSelect } from '@nextcloud/vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'

const props = defineProps({
	family: {
		type: Object,
		required: true,
	},
	editing: {
		type: Boolean,
		default: false,
	},
})

const emit = defineEmits(['update'])

const ibanValidation = ref(null)
const allMembers = ref([])
const membersLoading = ref(false)
const hideAlreadyInFamily = ref(true)
const selectedMember = ref(null)

onMounted(() => {
	if (props.editing) {
		loadAllMembers()
	}
})

watch(() => props.editing, (val) => {
	if (val && allMembers.value.length === 0) {
		loadAllMembers()
	}
})

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 filteredMemberOptions = computed(() => {
	let members = allMembers.value
	if (hideAlreadyInFamily.value) {
		members = members.filter(m => !m.familyId)
	}
	// Deduplicate by last name and build options
	const seen = new Set()
	const options = []
	for (const m of members) {
		const label = `${m.nachname}, ${m.vorname}`
		options.push({ value: m.nachname, label })
		seen.add(m.nachname)
	}
	return options
})

function onMemberSelected(nachname) {
	selectedMember.value = nachname
	if (nachname) {
		emit('update', 'name', nachname)
	}
}

const ibanValidationClass = computed(() => {
	if (ibanValidation.value === null) return ''
	return ibanValidation.value === 'Gültig'
		? 'family-form__iban-valid'
		: 'family-form__iban-invalid'
})

/**
 * Handle IBAN input with basic client-side validation feedback.
 */
function onIbanInput(value) {
	emit('update', 'ibanEncrypted', value)

	if (!value || value.trim() === '') {
		ibanValidation.value = null
		return
	}

	// Basic IBAN format check (will be properly validated on the backend)
	const cleaned = value.replace(/\s+/g, '').toUpperCase()
	if (cleaned.length < 15 || cleaned.length > 34) {
		ibanValidation.value = 'Ungültige Länge'
		return
	}

	if (!/^[A-Z]{2}[0-9]{2}[A-Z0-9]+$/.test(cleaned)) {
		ibanValidation.value = 'Ungültiges Format'
		return
	}

	// MOD-97 check
	if (validateIbanChecksum(cleaned)) {
		ibanValidation.value = 'Gültig'
	} else {
		ibanValidation.value = 'Ungültige Prüfsumme'
	}
}

/**
 * Validate IBAN checksum using MOD-97 algorithm.
 */
function validateIbanChecksum(iban) {
	// Move first 4 chars to end
	const rearranged = iban.substring(4) + iban.substring(0, 4)

	// Convert letters to numbers (A=10, B=11, etc.)
	let numericStr = ''
	for (const char of rearranged) {
		if (char >= 'A' && char <= 'Z') {
			numericStr += (char.charCodeAt(0) - 55).toString()
		} else {
			numericStr += char
		}
	}

	// MOD-97 on the large number (process in chunks to avoid overflow)
	let remainder = 0
	for (let i = 0; i < numericStr.length; i++) {
		remainder = (remainder * 10 + parseInt(numericStr[i])) % 97
	}

	return remainder === 1
}

watch(() => props.family.ibanEncrypted, (val) => {
	if (!props.editing) {
		ibanValidation.value = null
	}
})
</script>

<style scoped>
.family-form__row {
	display: flex;
	flex-direction: column;
	gap: 4px;
	margin-bottom: 16px;
}

.family-form__label {
	font-weight: 500;
	font-size: 0.9em;
	color: var(--color-text-lighter);
}

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

.family-form__section h4 {
	margin: 0 0 16px 0;
}

.family-form__iban-wrapper {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.family-form__iban-valid {
	color: var(--color-success);
	font-size: 0.85em;
}

.family-form__iban-invalid {
	color: var(--color-error);
	font-size: 0.85em;
}

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

.family-form__filter-label {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 0.85em;
	color: var(--color-text-lighter);
	cursor: pointer;
}

.family-form__checkbox {
	cursor: pointer;
}
</style>
