<template>
	<div class="injury-form__dialog-backdrop">
		<div class="injury-form__dialog">
			<h3>{{ isEdit ? 'Verletzung bearbeiten' : 'Neue Verletzung dokumentieren' }}</h3>
			<div class="injury-form__body">
				<label>Datum *
					<input v-model="form.datum" type="date">
				</label>
				<label>Uhrzeit
					<input v-model="form.uhrzeit" type="time">
				</label>
				<label>Betroffenes Mitglied *
					<NcSelect :model-value="form.memberId"
						:options="memberOptions"
						:reduce="o => o.value"
						label="label"
						placeholder="Mitglied auswählen..."
						:loading="membersLoading"
						:clearable="true"
						:disabled="fixedMemberId !== null"
						@update:model-value="form.memberId = $event" />
				</label>
				<label>Lager (optional)
					<NcSelect :model-value="form.lagerId"
						:options="lagerOptions"
						:reduce="o => o.value"
						label="label"
						placeholder="Lager auswählen..."
						:loading="lagerLoading"
						:clearable="true"
						:disabled="fixedLagerId !== null"
						@update:model-value="form.lagerId = $event" />
				</label>
				<label>Aktivität (wenn kein Lager)
					<input v-model="form.activityName"
						type="text"
						placeholder="z.B. Gruppenstunde, Wanderung">
				</label>
				<label>Beschreibung *
					<textarea v-model="form.beschreibung"
						rows="4"
						placeholder="Was ist passiert? Welche Massnahmen wurden ergriffen?" />
				</label>
				<label>Beteiligte Mitglieder
					<NcSelect :model-value="involvedMemberIds"
						:options="involvedMemberOptions"
						:reduce="o => o.value"
						label="label"
						placeholder="Mitglieder auswählen..."
						:loading="membersLoading"
						:multiple="true"
						:close-on-select="false"
						@update:model-value="involvedMemberIds = $event" />
				</label>
			</div>
			<div class="injury-form__actions">
				<NcButton @click="$emit('close')">
					Abbrechen
				</NcButton>
				<NcButton type="primary"
					:disabled="!isValid"
					@click="doSubmit">
					{{ isEdit ? 'Speichern' : 'Erstellen' }}
				</NcButton>
			</div>
		</div>
	</div>
</template>

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

const props = defineProps({
	injury: { type: Object, default: null },
	fixedMemberId: { type: Number, default: null },
	fixedLagerId: { type: Number, default: null },
})

const emit = defineEmits(['close', 'submit'])

const isEdit = computed(() => !!props.injury)

const form = ref({
	datum: props.injury?.datum || new Date().toISOString().substring(0, 10),
	uhrzeit: props.injury?.uhrzeit || null,
	memberId: props.injury?.memberId || props.fixedMemberId || null,
	lagerId: props.injury?.lagerId || props.fixedLagerId || null,
	activityName: props.injury?.activityName || '',
	beschreibung: props.injury?.beschreibung || '',
})

const involvedMemberIds = ref(
	props.injury?.involvedMembers?.map(m => m.memberId) || [],
)

const isValid = computed(() => {
	return form.value.datum
		&& form.value.memberId
		&& form.value.beschreibung?.trim()
})

watch(() => props.fixedMemberId, (val) => {
	if (val !== null) form.value.memberId = val
})

watch(() => props.fixedLagerId, (val) => {
	if (val !== null) form.value.lagerId = val
})

// ── Load members ────────────────────────────────────────────────────
const allMembers = ref([])
const membersLoading = ref(false)

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 memberOptions = computed(() =>
	allMembers.value.map(m => ({
		value: m.id,
		label: `${m.nachname}, ${m.vorname}`,
	})),
)

const involvedMemberOptions = computed(() =>
	allMembers.value
		.filter(m => m.id !== form.value.memberId)
		.map(m => ({
			value: m.id,
			label: `${m.nachname}, ${m.vorname}`,
		})),
)

// ── Load camps ──────────────────────────────────────────────────────
const allCamps = ref([])
const lagerLoading = ref(false)

async function loadAllCamps() {
	lagerLoading.value = true
	try {
		const url = generateUrl('/apps/mitgliederverwaltung/api/v1/lager')
		const response = await axios.get(url)
		allCamps.value = response.data.data || []
	} catch {
		allCamps.value = []
	} finally {
		lagerLoading.value = false
	}
}

const lagerOptions = computed(() =>
	allCamps.value.map(c => ({
		value: c.id,
		label: `${c.name} (${c.startdatum})`,
	})),
)

onMounted(() => {
	loadAllMembers()
	loadAllCamps()
})

function doSubmit() {
	emit('submit', {
		...form.value,
		involvedMemberIds: involvedMemberIds.value,
	})
}
</script>

<style scoped>
.injury-form__dialog-backdrop { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
.injury-form__dialog { background: var(--color-main-background); padding: 24px; border-radius: 12px; width: 520px; max-width: 90vw; max-height: 90vh; overflow-y: auto; }
.injury-form__body { display: flex; flex-direction: column; gap: 12px; margin: 16px 0; }
.injury-form__body label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; font-size: 13px; }
.injury-form__body input, .injury-form__body textarea { padding: 6px 8px; border: 1px solid var(--color-border); border-radius: 4px; width: 100%; box-sizing: border-box; }
.injury-form__actions { display: flex; justify-content: flex-end; gap: 8px; }
</style>
