<template>
	<div class="stock-item-form">
		<form @submit.prevent="handleSubmit">
			<div class="stock-item-form__field">
				<label for="si-name">Name:</label>
				<NcTextField
					id="si-name"
					:model-value="form.name"
					:placeholder="'Name des Verkaufsmaterials'"
					:validate="form.name !== ''"
					@update:model-value="form.name = $event"
					required
				/>
			</div>

			<div class="stock-item-form__field">
				<label for="si-categories">Kategorien:</label>
				<NcSelect
					id="si-categories"
					:model-value="categoryOptions.filter(o => form.categories?.includes(o.value))"
					:options="categoryOptions"
					multiple
					:reduce="o => o.value"
					:close-on-select="false"
					@update:model-value="form.categories = $event.map(o => o.value)"
				/>
			</div>

			<div class="stock-item-form__field">
				<label>Provider-URLs:</label>
				<div v-for="(urlEntry, idx) in form.providerUrls" :key="idx" class="stock-item-form__url-row">
					<NcTextField
						:model-value="urlEntry.url"
						:placeholder="'https://...'"
						@update:model-value="form.providerUrls[idx].url = $event"
					/>
					<NcTextField
						:model-value="urlEntry.provider"
						:placeholder="'Provider'"
						@update:model-value="form.providerUrls[idx].provider = $event"
					/>
					<NcButton type="tertiary-no-background" @click="removeUrl(idx)">
						<template #icon>
							<Close :size="20" />
						</template>
					</NcButton>
				</div>
				<NcButton type="tertiary" @click="addUrl">
					<template #icon>
						<Plus :size="20" />
					</template>
					URL hinzufügen
				</NcButton>
			</div>

			<div class="stock-item-form__variants-header">
				<span>Varianten:</span>
				<NcButton type="tertiary" @click="addVariant">
					<template #icon>
						<Plus :size="20" />
					</template>
					Variante hinzufügen
				</NcButton>
			</div>

			<div v-for="(variant, idx) in form.variants" :key="idx" class="stock-item-form__variant-row">
				<NcTextField
					:model-value="variant.label"
					:placeholder="'Größe M, Farbe Blau...'"
					:validate="variant.label !== ''"
					@update:model-value="form.variants[idx].label = $event"
				/>
				<NcTextField
					:type="'number'"
					:model-value="variant.amount"
					:validate="variant.amount >= 0"
					@update:model-value="form.variants[idx].amount = Number($event) || 0"
				/>
				<NcTextField
					:type="'text'"
					:model-value="variant.cost"
					:placeholder="'Stückpreis (€)'"
					@update:model-value="variant.cost = $event"
				/>
				<NcTextField
					:type="'number'"
					:model-value="variant.min_threshold"
					:validate="variant.min_threshold >= 0"
					@update:model-value="form.variants[idx].min_threshold = Number($event) || 0"
				/>
				<NcButton type="tertiary-no-background" @click="removeVariant(idx)">
					<template #icon>
						<Close :size="20" />
					</template>
				</NcButton>
			</div>

			<div class="stock-item-form__actions">
				<NcButton type="tertiary" @click="$emit('close')">
					Abbrechen
				</NcButton>
				<NcButton type="primary" :disabled="!isFormValid" @click="handleSubmit">
					{{ form.name ? (editMode ? 'Speichern' : 'Erstellen') : 'Speichern' }}
				</NcButton>
			</div>
		</form>
	</div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { NcTextField, NcSelect, NcButton } from '@nextcloud/vue'
import Close from 'vue-material-design-icons/Close.vue'
import Plus from 'vue-material-design-icons/Plus.vue'

const props = defineProps({
	item: {
		type: Object,
		default: null,
	},
	categories: {
		type: Array,
		default: () => [],
	},
})

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

const editMode = computed(() => !!props.item)

const form = ref({
	name: '',
	categories: [],
	providerUrls: [],
	variants: [],
})

const categoryOptions = computed(() => {
	return props.categories.map(c => ({
		value: c.id,
		label: c.name,
	}))
})

const isFormValid = computed(() => form.value.name !== '')

// Load existing item data
watch(() => props.item, (newVal) => {
	if (newVal) {
		let urls = []
		try {
			urls = JSON.parse(newVal.provider_urls_json || '[]')
		} catch {
			urls = []
		}

		form.value = {
			name: newVal.name || '',
			categories: newVal.categories || [],
			providerUrls: urls.map(u => ({ url: u.url || '', provider: u.provider || '' })),
			variants: (newVal.variants || []).map(v => ({
				id: v.id,
				label: v.label || '',
				amount: v.amount || 0,
				cost: v.cost || '0.00',
				min_threshold: v.min_threshold || 0,
			})),
		}
	}
}, { immediate: true })

function addUrl() {
	form.value.providerUrls.push({ url: '', provider: '' })
}

function removeUrl(idx) {
	form.value.providerUrls.splice(idx, 1)
}

function addVariant() {
	form.value.variants.push({
		label: '',
		amount: 0,
		cost: '0.00',
		min_threshold: 0,
	})
}

function removeVariant(idx) {
	form.value.variants.splice(idx, 1)
}

async function handleSubmit() {
	if (!isFormValid.value) return

	const data = {
		name: form.value.name,
		categories: form.value.categories,
		provider_urls_json: JSON.stringify(form.value.providerUrls),
		variants: form.value.variants.map(v => ({
			label: v.label,
			amount: v.amount || 0,
			cost: v.cost || '0.00',
			min_threshold: v.min_threshold || 0,
			id: v.id,
		})),
	}

	if (editMode.value) {
		await emit('update', 'stock', 'update', { id: props.item.id, ...data })
	} else {
		await emit('update', 'stock', 'create', data)
	}
}
</script>

<style scoped>
.stock-item-form {
	max-width: 600px;
}

.stock-item-form__field {
	margin-bottom: 16px;
}

.stock-item-form__field label {
	display: block;
	margin-bottom: 4px;
	font-weight: 600;
	font-size: 14px;
}

.stock-item-form__url-row,
.stock-item-form__variant-row {
	display: flex;
	gap: 8px;
	align-items: center;
	margin-bottom: 8px;
	flex-wrap: wrap;
}

.stock-item-form__variants-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin: 16px 0 8px;
}

.stock-item-form__actions {
	display: flex;
	gap: 8px;
	justify-content: flex-end;
	margin-top: 24px;
}
</style>
