<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from "vue";
import { apiDelete, apiGet, apiPost, apiPut } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import { matchesObjectSearch, reserveNextNumber } from "../number-ranges";
import { liveUpdateState } from "../realtime";
import type { Item, ItemPriceHistory } from "../types";

const emptyForm = () => ({ item_number: "", name: "", unit: "Stk", tax_rate: "19", default_purchase_price: null as string | null, default_sales_price: null as string | null, status: "active" });
const items = ref<Item[]>([]);
const priceHistory = ref<ItemPriceHistory[]>([]);
const selectedId = ref<string | null>(null);
const form = reactive(emptyForm());
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");
const search = ref("");
const filteredItems = computed(() =>
  items.value.filter((item) => matchesObjectSearch(item.item_number, item.name, search.value))
);
async function load() { const r = await apiGet<Item[]>("/api/v1/items"); if (r.ok) items.value = r.data; else { status.value = r.message; kind.value = "error"; } }
async function createNew() { selectedId.value = null; Object.assign(form, emptyForm()); form.item_number = (await reserveNextNumber("items")) ?? ""; priceHistory.value = []; }
async function select(item: Item) { selectedId.value = item.id; Object.assign(form, item); await loadPriceHistory(item.id); }
async function loadPriceHistory(itemId: string) {
  const result = await apiGet<ItemPriceHistory[]>(`/api/v1/items/${itemId}/prices`);
  if (result.ok) priceHistory.value = result.data;
}
async function save() {
  const r = selectedId.value ? await apiPut<Item>(`/api/v1/items/${selectedId.value}`, form) : await apiPost<Item>("/api/v1/items", form);
  status.value = r.ok ? "Artikel gespeichert." : r.message; kind.value = r.ok ? "success" : "error"; if (r.ok) { selectedId.value = r.data.id; await Promise.all([load(), loadPriceHistory(r.data.id)]); }
}
async function deactivate() { if (!selectedId.value) return; const r = await apiDelete(`/api/v1/items/${selectedId.value}`); status.value = r.ok ? "Artikel deaktiviert." : r.message; kind.value = r.ok ? "success" : "error"; if (r.ok) await load(); }
onMounted(load); watch(() => liveUpdateState.revision, async () => { await load(); if (selectedId.value) await loadPriceHistory(selectedId.value); });
</script>
<template>
  <PageHeader title="Artikel" description="Artikelstamm und aktuelle Standardpreise." />
  <div class="workspace-split">
    <section class="panel list-panel">
      <div class="section-title"><h2>Artikel</h2><button type="button" @click="createNew">Neu</button></div>
      <label class="field list-search"><span>Suche</span><input v-model="search" type="search" placeholder="Artikelnummer oder Bezeichnung" /></label>
      <button v-for="item in filteredItems" :key="item.id" type="button" class="list-row" :class="{ selected: selectedId === item.id }" @click="select(item)"><strong>{{ item.item_number }}</strong><span>{{ item.name }}</span><small>{{ item.status }}</small></button>
      <p v-if="items.length === 0" class="empty">Keine Artikel vorhanden.</p>
      <p v-else-if="filteredItems.length === 0" class="empty">Keine Treffer.</p>
    </section>
    <section class="panel detail-panel">
      <form @submit.prevent="save"><div class="form-grid">
        <label class="field"><span>Artikelnummer</span><div class="readonly-value">{{ form.item_number || "wird automatisch vergeben" }}</div></label>
        <label class="field"><span>Bezeichnung</span><input v-model="form.name" required /></label>
        <label class="field"><span>Einheit</span><input v-model="form.unit" required /></label>
        <label class="field"><span>Steuersatz %</span><input v-model="form.tax_rate" type="number" min="0" step="0.01" required /></label>
        <label class="field"><span>Einkaufspreis</span><input v-model="form.default_purchase_price" type="number" min="0" step="0.01" /></label>
        <label class="field"><span>Verkaufspreis</span><input v-model="form.default_sales_price" type="number" min="0" step="0.01" /></label>
        <label class="field"><span>Status</span><select v-model="form.status"><option value="active">Aktiv</option><option value="inactive">Inaktiv</option><option value="blocked">Gesperrt</option></select></label>
      </div><div class="form-actions"><button type="submit">Speichern</button><button v-if="selectedId" type="button" class="secondary" @click="deactivate">Deaktivieren</button></div><FormStatus :message="status" :kind="kind" /></form>
      <div v-if="selectedId" class="sub-panel">
        <h2>Preishistorie</h2>
        <div v-for="entry in priceHistory" :key="entry.id" class="data-row">
          <strong>{{ new Date(entry.valid_from).toLocaleString("de-DE") }}</strong>
          <span>EK {{ entry.purchase_price ?? "-" }}</span>
          <span>VK {{ entry.sales_price ?? "-" }}</span>
          <small>{{ entry.source }}</small>
        </div>
        <p v-if="priceHistory.length === 0" class="empty">Noch keine Preisänderung vorhanden.</p>
      </div>
    </section>
  </div>
</template>
