<template>
	<div class="sub-entity-list">
		<!-- Existing items -->
		<div v-for="(item, index) in items"
			:key="item.id || index"
			class="sub-entity-list__item">
			<div class="sub-entity-list__fields">
				<div v-for="field in fields"
					:key="field.key"
					class="sub-entity-list__field">
					<template v-if="field.type === 'checkbox'">
						<label class="sub-entity-list__checkbox-label">
							<input type="checkbox"
								:checked="item[field.key]"
								:disabled="!editing"
								@change="$emit('update', index, field.key, $event.target.checked)">
							{{ field.label }}
						</label>
					</template>
					<template v-else>
						<label>{{ field.label }}{{ field.required ? ' *' : '' }}</label>
						<NcTextField :model-value="item[field.key] || ''"
							:disabled="!editing"
							:placeholder="field.placeholder || ''"
							@update:model-value="$emit('update', index, field.key, $event)" />
					</template>
				</div>
			</div>
			<NcButton v-if="editing"
				type="tertiary"
				@click="$emit('remove', index)">
				<template #icon>
					<Delete :size="20" />
				</template>
			</NcButton>
		</div>

		<!-- Empty state -->
		<p v-if="items.length === 0" class="sub-entity-list__empty">
			Keine {{ entityName }} vorhanden.
		</p>

		<!-- Add button -->
		<NcButton v-if="editing"
			type="secondary"
			@click="$emit('add')">
			<template #icon>
				<Plus :size="20" />
			</template>
			{{ entityName }} hinzufügen
		</NcButton>
	</div>
</template>

<script setup>
import { NcButton, NcTextField } from '@nextcloud/vue'
import Delete from 'vue-material-design-icons/Delete.vue'
import Plus from 'vue-material-design-icons/Plus.vue'

defineProps({
	items: {
		type: Array,
		required: true,
	},
	fields: {
		type: Array,
		required: true,
	},
	editing: {
		type: Boolean,
		default: false,
	},
	entityName: {
		type: String,
		default: 'Eintrag',
	},
})

defineEmits(['add', 'update', 'remove'])
</script>

<style scoped>
.sub-entity-list__item {
	display: flex;
	align-items: flex-start;
	gap: 12px;
	padding: 12px;
	margin-bottom: 8px;
	background: var(--color-background-dark);
	border-radius: var(--border-radius-large);
}

.sub-entity-list__fields {
	flex: 1;
	display: grid;
	grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
	gap: 12px;
}

.sub-entity-list__field {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.sub-entity-list__field label {
	font-size: 0.85em;
	color: var(--color-text-lighter);
	font-weight: 500;
}

.sub-entity-list__checkbox-label {
	display: flex;
	align-items: center;
	gap: 6px;
	font-size: 0.9em;
	cursor: pointer;
}

.sub-entity-list__empty {
	color: var(--color-text-lighter);
	font-style: italic;
	margin: 8px 0;
}
</style>
