<template>
	<div class="fee-editor">
		<h3>Beitragsregeln</h3>
		<p class="fee-editor__description">
			Konfigurieren Sie die Beitragsregeln mit Familienstaffelung.
			Neue Regeln ersetzen alte nicht -- sie sind versioniert ab dem angegebenen Jahr.
		</p>

		<!-- Error / Success messages -->
		<div v-if="feesStore.error" class="fee-editor__error">
			{{ feesStore.error }}
			<NcButton @click="feesStore.clearError()">Schließen</NcButton>
		</div>
		<div v-if="feesStore.success" class="fee-editor__success">
			{{ feesStore.success }}
			<NcButton @click="feesStore.clearSuccess()">Schließen</NcButton>
		</div>

		<!-- Loading -->
		<NcLoadingIcon v-if="feesStore.loading && feesStore.rules.length === 0"
			:size="32"
			class="fee-editor__loading" />

		<!-- ── New Rule Form ──────────────────────────────────────────── -->
		<div class="fee-editor__form">
			<h4>Neue Regel erstellen</h4>

			<div class="fee-editor__form-row">
				<div class="fee-editor__field">
					<label for="fee-year-from">Gültig ab Jahr</label>
					<input id="fee-year-from"
						v-model.number="newRule.yearFrom"
						type="number"
						min="2020"
						max="2100"
						class="fee-editor__input">
				</div>

				<div class="fee-editor__field">
					<label for="fee-base-rate">Grundbeitrag</label>
					<div class="fee-editor__currency-input">
						<input id="fee-base-rate"
							v-model="newRule.baseRate"
							type="number"
							min="0"
							step="0.01"
							class="fee-editor__input">
						<span class="fee-editor__currency">EUR</span>
					</div>
				</div>
			</div>

			<!-- Family Rules Table -->
			<div class="fee-editor__family-rules">
				<label>Familienstaffelung</label>
				<p class="fee-editor__hint">
					Legen Sie fest, welcher Beitrag pro Kind je nach Anzahl der Kinder in der Familie gilt.
					Verwenden Sie "3+" für "drittes Kind und weitere".
				</p>

				<table class="fee-editor__table">
					<thead>
						<tr>
							<th>Position / Regel</th>
							<th>Beitrag pro Kind (EUR)</th>
							<th />
						</tr>
					</thead>
					<tbody>
						<tr v-for="(row, index) in newRule.familyRows" :key="index">
							<td>
								<input v-model="row.key"
									type="text"
									placeholder="z.B. 1, 2, 3+"
									class="fee-editor__input fee-editor__input--small">
							</td>
							<td>
								<input v-model.number="row.value"
									type="number"
									min="0"
									step="0.01"
									class="fee-editor__input fee-editor__input--small">
							</td>
							<td>
								<button class="fee-editor__remove-btn"
									title="Zeile entfernen"
									@click="removeFamilyRow(index)">
									&#10005;
								</button>
							</td>
						</tr>
					</tbody>
				</table>

				<NcButton type="secondary" @click="addFamilyRow">
					<template #icon>
						<Plus :size="20" />
					</template>
					Zeile hinzufügen
				</NcButton>
			</div>

			<!-- Inactive rule display (read-only) -->
			<div class="fee-editor__inactive-rule">
				<label>Regel für inaktive Mitglieder</label>
				<p class="fee-editor__hint">
					Aktuell: Beitrag wird beim Austritt eingefroren (freeze_rate_at_exit)
				</p>
			</div>

			<!-- Preview Section -->
			<div class="fee-editor__preview">
				<h4>Vorschau</h4>
				<div class="fee-editor__preview-controls">
					<label for="preview-family-size">Familiengroesse (Kinder)</label>
					<input id="preview-family-size"
						v-model.number="previewFamilySize"
						type="number"
						min="0"
						max="10"
						class="fee-editor__input fee-editor__input--small">
				</div>

				<div class="fee-editor__preview-results">
					<table class="fee-editor__table fee-editor__table--preview">
						<thead>
							<tr>
								<th>Kind</th>
								<th>Beitrag</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="n in previewFamilySize" :key="n">
								<td>{{ n }}. Kind</td>
								<td>{{ formatCurrency(getPreviewFeeForPosition(n)) }}</td>
							</tr>
							<tr v-if="previewFamilySize > 0" class="fee-editor__preview-total">
								<td><strong>Gesamt</strong></td>
								<td><strong>{{ formatCurrency(previewTotal) }}</strong></td>
							</tr>
							<tr v-if="previewFamilySize === 0">
								<td colspan="2" class="fee-editor__preview-empty">
									Einzelmitglied: {{ formatCurrency(parseFloat(newRule.baseRate) || 0) }}
								</td>
							</tr>
						</tbody>
					</table>
				</div>
			</div>

			<!-- Save button -->
			<div class="fee-editor__actions">
				<NcButton type="primary"
					:disabled="!isFormValid || feesStore.loading"
					@click="saveRule">
					Regel speichern
				</NcButton>
			</div>
		</div>

		<!-- ── Rule History ───────────────────────────────────────────── -->
		<div v-if="feesStore.rules.length > 0" class="fee-editor__history">
			<h4>Bisherige Regeln</h4>
			<table class="fee-editor__table fee-editor__table--history">
				<thead>
					<tr>
						<th>Gültig ab</th>
						<th>Grundbeitrag</th>
						<th>Familienstaffelung</th>
						<th>Erstellt am</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="rule in feesStore.rules"
						:key="rule.id"
						:class="{ 'fee-editor__row--current': rule.id === feesStore.currentRule?.id }">
						<td>{{ rule.yearFrom }}</td>
						<td>{{ formatCurrency(parseFloat(rule.baseRate)) }}</td>
						<td>
							<span v-for="(value, key) in rule.familyRules"
								:key="key"
								class="fee-editor__rule-badge">
								{{ key }}: {{ formatCurrency(parseFloat(value)) }}
							</span>
							<span v-if="!rule.familyRules || Object.keys(rule.familyRules).length === 0"
								class="fee-editor__no-rules">
								Keine Staffelung
							</span>
						</td>
						<td>{{ formatDate(rule.createdAt) }}</td>
					</tr>
				</tbody>
			</table>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, computed, onMounted } from 'vue'
import { NcButton, NcLoadingIcon } from '@nextcloud/vue'
import { useFeesStore } from '../stores/fees.js'
import Plus from 'vue-material-design-icons/Plus.vue'
import { formatDate } from '../utils/dateFormat.js'

const feesStore = useFeesStore()

// ── Form state ──────────────────────────────────────────────────────

const newRule = reactive({
	yearFrom: new Date().getFullYear(),
	baseRate: '60.00',
	familyRows: [
		{ key: '1', value: 60 },
		{ key: '2', value: 45 },
		{ key: '3+', value: 30 },
	],
})

const previewFamilySize = ref(2)

// ── Computed ────────────────────────────────────────────────────────

const isFormValid = computed(() => {
	if (!newRule.yearFrom || newRule.yearFrom < 2020) return false
	if (!newRule.baseRate || parseFloat(newRule.baseRate) < 0) return false
	// Validate family rows: all keys must be non-empty, all values >= 0
	for (const row of newRule.familyRows) {
		if (!row.key || row.key.trim() === '') return false
		if (row.value === null || row.value === undefined || row.value < 0) return false
	}
	return true
})

/**
 * Build the family rules object from the table rows.
 */
const familyRulesObject = computed(() => {
	const rules = {}
	for (const row of newRule.familyRows) {
		if (row.key && row.key.trim() !== '') {
			rules[row.key.trim()] = row.value
		}
	}
	return rules
})

/**
 * Get the preview fee for a given child position using the current form rules.
 */
function getPreviewFeeForPosition(position) {
	const rules = familyRulesObject.value
	const posKey = String(position)

	// Exact match
	if (rules[posKey] !== undefined) {
		return rules[posKey]
	}

	// Check catch-all rules (e.g. "3+")
	for (let i = position; i >= 1; i--) {
		const catchAllKey = i + '+'
		if (rules[catchAllKey] !== undefined) {
			return rules[catchAllKey]
		}
	}

	// Fallback to base rate
	return parseFloat(newRule.baseRate) || 0
}

const previewTotal = computed(() => {
	let total = 0
	for (let n = 1; n <= previewFamilySize.value; n++) {
		total += getPreviewFeeForPosition(n)
	}
	return total
})

// ── Actions ─────────────────────────────────────────────────────────

onMounted(() => {
	feesStore.fetchRules()
})

function addFamilyRow() {
	const nextPosition = newRule.familyRows.length + 1
	newRule.familyRows.push({ key: String(nextPosition), value: 0 })
}

function removeFamilyRow(index) {
	newRule.familyRows.splice(index, 1)
}

async function saveRule() {
	try {
		await feesStore.createRule({
			yearFrom: newRule.yearFrom,
			baseRate: String(newRule.baseRate),
			familyRules: familyRulesObject.value,
		})
	} catch {
		// Error displayed by store
	}
}

// ── Formatting helpers ──────────────────────────────────────────────

function formatCurrency(value) {
	if (value === null || value === undefined || isNaN(value)) return '--'
	return new Intl.NumberFormat('de-DE', {
		style: 'currency',
		currency: 'EUR',
	}).format(value)
}

// formatDate imported from utils/dateFormat.js
</script>

<style scoped>
.fee-editor {
	margin-top: 8px;
}

.fee-editor h3 {
	margin: 0 0 8px 0;
}

.fee-editor h4 {
	margin: 16px 0 8px 0;
	font-size: 1em;
}

.fee-editor__description {
	color: var(--color-text-lighter);
	margin: 0 0 16px 0;
}

.fee-editor__hint {
	color: var(--color-text-lighter);
	font-size: 0.85em;
	margin: 4px 0 8px 0;
}

.fee-editor__error {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 8px 12px;
	background: var(--color-error);
	color: white;
	border-radius: var(--border-radius);
	margin-bottom: 12px;
}

.fee-editor__success {
	display: flex;
	align-items: center;
	gap: 12px;
	padding: 8px 12px;
	background: var(--color-success);
	color: white;
	border-radius: var(--border-radius);
	margin-bottom: 12px;
}

.fee-editor__loading {
	margin: 20px 0;
}

.fee-editor__form {
	background: var(--color-background-dark);
	padding: 16px;
	border-radius: var(--border-radius);
	margin-bottom: 24px;
}

.fee-editor__form-row {
	display: flex;
	gap: 16px;
	flex-wrap: wrap;
	margin-bottom: 16px;
}

.fee-editor__field {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.fee-editor__field label {
	font-size: 0.85em;
	font-weight: 500;
	color: var(--color-text-lighter);
}

.fee-editor__input {
	padding: 6px 8px;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	background: var(--color-main-background);
	color: var(--color-text);
	width: 140px;
}

.fee-editor__input--small {
	width: 100px;
}

.fee-editor__currency-input {
	display: flex;
	align-items: center;
	gap: 4px;
}

.fee-editor__currency {
	color: var(--color-text-lighter);
	font-size: 0.85em;
}

/* Family rules table */
.fee-editor__family-rules {
	margin-bottom: 16px;
}

.fee-editor__family-rules > label {
	font-size: 0.85em;
	font-weight: 500;
	color: var(--color-text-lighter);
}

.fee-editor__table {
	width: 100%;
	border-collapse: collapse;
	margin: 8px 0;
}

.fee-editor__table th,
.fee-editor__table td {
	padding: 6px 8px;
	text-align: left;
	border-bottom: 1px solid var(--color-border);
}

.fee-editor__table th {
	font-size: 0.85em;
	font-weight: 500;
	color: var(--color-text-lighter);
}

.fee-editor__remove-btn {
	background: none;
	border: 1px solid var(--color-border);
	border-radius: var(--border-radius);
	cursor: pointer;
	color: var(--color-error);
	padding: 2px 6px;
	font-size: 0.9em;
}

.fee-editor__remove-btn:hover {
	background: var(--color-error);
	color: white;
}

/* Inactive rule */
.fee-editor__inactive-rule {
	margin-bottom: 16px;
}

.fee-editor__inactive-rule > label {
	font-size: 0.85em;
	font-weight: 500;
	color: var(--color-text-lighter);
}

/* Preview */
.fee-editor__preview {
	background: var(--color-main-background);
	padding: 12px;
	border-radius: var(--border-radius);
	border: 1px solid var(--color-border);
	margin-bottom: 16px;
}

.fee-editor__preview-controls {
	display: flex;
	align-items: center;
	gap: 8px;
	margin-bottom: 8px;
}

.fee-editor__preview-controls label {
	font-size: 0.85em;
	color: var(--color-text-lighter);
}

.fee-editor__table--preview {
	max-width: 300px;
}

.fee-editor__preview-total td {
	border-top: 2px solid var(--color-border);
}

.fee-editor__preview-empty {
	color: var(--color-text-lighter);
	font-style: italic;
}

/* Actions */
.fee-editor__actions {
	margin-top: 16px;
}

/* History table */
.fee-editor__history {
	margin-top: 24px;
}

.fee-editor__table--history {
	font-size: 0.9em;
}

.fee-editor__row--current {
	background: var(--color-primary-element-light);
}

.fee-editor__rule-badge {
	display: inline-block;
	padding: 2px 6px;
	margin: 1px 4px 1px 0;
	background: var(--color-background-dark);
	border-radius: var(--border-radius);
	font-size: 0.85em;
}

.fee-editor__no-rules {
	color: var(--color-text-lighter);
	font-style: italic;
	font-size: 0.85em;
}
</style>
