<template>
	<div class="sale-form">
		<form @submit.prevent="handleSubmit">
			<div class="sale-form__field">
				<label for="sale-item">Artikel:</label>
				<NcSelect
					id="sale-item"
					:model-value="stockItemOptions.find(o => o.value === form.stock_item_id)"
					:options="stockItemOptions"
					:reduce="o => o.value"
					:clearable="true"
					@update:model-value="form.stock_item_id = $event"
					placeholder="Artikel auswählen..."
				/>
			</div>

			<div class="sale-form__field">
				<label for="sale-date">Datum:</label>
				<NcDateTimePicker
					id="sale-date"
					:model-value="form.date ? new Date(form.date + 'T00:00:00') : new Date()"
					@update:model-value="form.date = $event?.toISOString().split('T')[0] || (new Date()).toISOString().split('T')[0]"
				/>
			</div>

			<div class="sale-form__field">
				<label for="sale-variant">Variante:</label>
				<NcSelect
					id="sale-variant"
					:model-value="variantOptions.find(o => o.value === form.variant_id)"
					:options="variantOptions"
					:reduce="o => o.value"
					:clearable="true"
					:disabled="!form.stock_item_id"
					@update:model-value="form.variant_id = $event"
					placeholder="Variante auswählen (optional)..."
				/>
			</div>

			<div class="sale-form__field">
				<label for="sale-quantity">Menge:</label>
				<NcTextField
					id="sale-quantity"
					:type="'number'"
					:model-value="form.quantity"
					:validate="form.quantity >= 1"
					@update:model-value="form.quantity = Number($event) || 0"
				/>
			</div>

			<div class="sale-form__field">
				<label for="sale-unit-price">Stückpreis (€):</label>
				<NcTextField
					id="sale-unit-price"
					:type="'text'"
					:model-value="form.unit_price"
					:validate="form.unit_price !== ''"
					@update:model-value="form.unit_price = $event"
					placeholder="0.00"
				/>
			</div>

			<div class="sale-form__field sale-form__field--summary">
				<strong>Gesamtsumme:</strong> {{ totalPrice }}
			</div>

			<div class="sale-form__field">
				<label for="sale-notes">Notizen:</label>
				<NcTextField
					id="sale-notes"
					:type="'textarea'"
					:model-value="form.notes"
					:placeholder="'Zusätzliche Notizen...'"
					:validate="true"
					@update:model-value="form.notes = $event"
				/>
			</div>

			<div class="sale-form__actions">
				<NcButton type="tertiary" @click="$emit('close')">
					Abbrechen
				</NcButton>
				<NcButton type="primary" :disabled="!isFormValid" @click="handleSubmit">
					Verkauf eintragen
				</NcButton>
			</div>
		</form>
	</div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { NcTextField, NcSelect, NcButton, NcDateTimePicker } from '@nextcloud/vue'

const props = defineProps({
	stockItems: {
		type: Array,
		default: () => [],
	},
})

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

const form = ref({
	stock_item_id: null,
	variant_id: null,
	date: new Date().toISOString().split('T')[0],
	quantity: 1,
	unit_price: '0.00',
	notes: '',
})

const stockItemOptions = computed(() => {
	return props.stockItems.map(item => ({
		value: item.id,
		label: item.name,
	}))
})

const variantOptions = computed(() => {
	if (!form.value.stock_item_id) return []
	const item = props.stockItems.find(i => i.id === form.value.stock_item_id)
	if (!item || !item.variants) return []
	return item.variants.map(v => ({
		value: v.id,
		label: v.label,
	}))
})

const totalPrice = computed(() => {
	const qty = Number(form.value.quantity) || 0
	const price = parseFloat(form.value.unit_price) || 0
	const total = qty * price
	return total.toLocaleString('de-DE', {
		style: 'currency',
		currency: 'EUR',
	})
})

const isFormValid = computed(() => {
	return form.value.stock_item_id !== null &&
		form.value.quantity >= 1 &&
		form.value.unit_price !== ''
})

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

	const data = {
		stock_item_id: form.value.stock_item_id,
		variant_id: form.value.variant_id,
		date: form.value.date,
		quantity: Number(form.value.quantity),
		unit_price: form.value.unit_price,
		notes: form.value.notes || null,
	}

	// Create the sale and notify the parent
	emit('create', data)
}
</script>

<style scoped>
.sale-form {
	max-width: 500px;
}

.sale-form__field {
	margin-bottom: 16px;
}

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

.sale-form__field--summary {
	background: var(--color-background-dark);
	padding: 12px;
	border-radius: var(--border-radius);
}

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