<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 SearchSelect from "../components/SearchSelect.vue";
import { formatDecimal, formatDecimalInput, formatEuro, normalizeDecimal, normalizeTaxRate, taxRateOptions, unitOptions } from "../format";
import { matchesObjectSearch, reserveNextNumber } from "../number-ranges";
import { liveUpdateState } from "../realtime";
import type { Item, ItemPriceHistory, ItemSupplierPrice, Supplier } from "../types";

const emptySupplierPrice = (): ItemSupplierPrice => ({ supplier_id: "", external_item_number: "", purchase_price: "0,00", currency: "EUR", is_preferred: false, valid_from: null, valid_until: null });
const emptyForm = () => ({ item_number: "", name: "", manufacturer_code: null as string | null, unit: "Stck", tax_rate: "19", default_purchase_price: null as string | null, default_sales_price: null as string | null, status: "active", supplier_prices: [] as ItemSupplierPrice[] });
const items = ref<Item[]>([]);
const suppliers = ref<Supplier[]>([]);
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 sortMode = ref<"name_desc" | "number_desc">("name_desc");
const filteredItems = computed(() =>
  items.value
    .filter((item) => matchesObjectSearch(item.item_number, item.name, search.value))
    .sort((left, right) => {
      if (sortMode.value === "number_desc") {
        return right.item_number.localeCompare(left.item_number, "de", { numeric: true, sensitivity: "base" });
      }
      return right.name.localeCompare(left.name, "de", { numeric: true, sensitivity: "base" });
    })
);
async function load() {
  const [itemResult, supplierResult] = await Promise.all([apiGet<Item[]>("/api/v1/items"), apiGet<Supplier[]>("/api/v1/suppliers")]);
  if (itemResult.ok) items.value = itemResult.data; else { status.value = itemResult.message; kind.value = "error"; }
  if (supplierResult.ok) suppliers.value = supplierResult.data.filter((supplier) => supplier.status === "active");
}
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, displayItem(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 payload = apiItemPayload();
  const r = selectedId.value ? await apiPut<Item>(`/api/v1/items/${selectedId.value}`, payload) : await apiPost<Item>("/api/v1/items", payload);
  status.value = r.ok ? "Artikel gespeichert." : r.message; kind.value = r.ok ? "success" : "error"; if (r.ok) { selectedId.value = r.data.id; Object.assign(form, displayItem(r.data)); 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(); }
function addSupplierPrice() { form.supplier_prices.push(emptySupplierPrice()); }
function removeSupplierPrice(index: number) { form.supplier_prices.splice(index, 1); }
function displayItem(item: Item) {
  return {
    ...item,
    tax_rate: normalizeTaxRate(item.tax_rate),
    default_purchase_price: formatDecimal(item.default_purchase_price),
    default_sales_price: formatDecimal(item.default_sales_price),
    supplier_prices: item.supplier_prices.map((price) => ({ ...price, purchase_price: formatDecimal(price.purchase_price) }))
  };
}
function apiItemPayload() {
  return {
    ...form,
    tax_rate: normalizeTaxRate(form.tax_rate),
    default_purchase_price: normalizeDecimal(form.default_purchase_price),
    default_sales_price: normalizeDecimal(form.default_sales_price),
    supplier_prices: form.supplier_prices.map((price) => ({
      ...price,
      purchase_price: normalizeDecimal(price.purchase_price) ?? "0",
      currency: price.currency.trim().toUpperCase()
    }))
  };
}
function selectedUnitValue() {
  return unitOptions.includes(form.unit) ? form.unit : "__custom";
}
function selectUnit(event: Event) {
  const value = (event.target as HTMLSelectElement).value;
  if (value === "__custom") {
    if (unitOptions.includes(form.unit)) form.unit = "";
  } else {
    form.unit = value;
  }
}
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>
      <label class="field list-search"><span>Sortierung</span><select v-model="sortMode"><option value="name_desc">Artikelname absteigend</option><option value="number_desc">Artikelnummer absteigend</option></select></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>Hersteller-Code</span><input v-model="form.manufacturer_code" /></label>
        <label class="field"><span>Bezeichnung</span><input v-model="form.name" required /></label>
        <label class="field"><span>Einheit</span><select :value="selectedUnitValue()" required @change="selectUnit"><option v-for="unit in unitOptions" :key="unit" :value="unit">{{ unit }}</option><option value="__custom">Eigene Einheit</option></select></label>
        <label v-if="selectedUnitValue() === '__custom'" class="field"><span>Eigene Einheit</span><input v-model="form.unit" required /></label>
        <label class="field"><span>Steuersatz %</span><select v-model="form.tax_rate" required><option v-for="rate in taxRateOptions" :key="rate" :value="rate">{{ rate }} %</option></select></label>
        <label class="field"><span>Einkaufspreis</span><input v-model="form.default_purchase_price" inputmode="decimal" @blur="formatDecimalInput(form, 'default_purchase_price')" /></label>
        <label class="field"><span>Verkaufspreis</span><input v-model="form.default_sales_price" inputmode="decimal" @blur="formatDecimalInput(form, 'default_sales_price')" /></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="sub-panel">
        <div class="section-title"><h2>Lieferantenpreise</h2><button type="button" @click="addSupplierPrice">Lieferant</button></div>
        <div v-for="(price, index) in form.supplier_prices" :key="index" class="quote-line">
          <label class="field full-width"><span>Lieferant</span><SearchSelect v-model="price.supplier_id" :options="suppliers.map((supplier) => ({ id: supplier.id, number: supplier.supplier_number, name: supplier.name }))" placeholder="Lieferanten-Nr. oder Name suchen" required /></label>
          <label class="field"><span>Externe Artikelnr.</span><input v-model="price.external_item_number" required /></label>
          <label class="field"><span>Einkaufspreis</span><input v-model="price.purchase_price" inputmode="decimal" required @blur="formatDecimalInput(price, 'purchase_price')" /></label>
          <label class="field"><span>Währung</span><input v-model="price.currency" maxlength="3" required /></label>
          <label class="check-row"><input v-model="price.is_preferred" type="checkbox" /><span>Bevorzugt</span></label>
          <button type="button" class="secondary" @click="removeSupplierPrice(index)">Entfernen</button>
        </div>
        <p v-if="form.supplier_prices.length === 0" class="empty">Keine Lieferantenpreise vorhanden.</p>
      </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 {{ formatEuro(entry.purchase_price) }}</span>
          <span>VK {{ formatEuro(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>
