<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 { decimalString } from "../format";
import { matchesObjectSearch, reserveNextNumber } from "../number-ranges";
import { liveUpdateState } from "../realtime";
import type { CashDiscountTerm, Supplier } from "../types";

const emptyForm = () => ({
  supplier_number: "", name: "", status: "active",
  details: { street: "", postal_code: "", city: "", country: "Deutschland", email: "", phone: "" },
  standard_discount_percent: "0", cash_discount_term_id: null as string | null, payment_days: 14 as number | null
});
const suppliers = ref<Supplier[]>([]);
const cashDiscountTerms = ref<CashDiscountTerm[]>([]);
const selectedId = ref<string | null>(null);
const form = reactive(emptyForm());
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");
const search = ref("");
const filteredSuppliers = computed(() =>
  suppliers.value.filter((supplier) => matchesObjectSearch(supplier.supplier_number, supplier.name, search.value))
);

async function load() {
  const result = await apiGet<Supplier[]>("/api/v1/suppliers");
  if (result.ok) suppliers.value = result.data;
  else { status.value = result.message; kind.value = "error"; }
}
async function loadCashDiscountTerms() {
  const result = await apiGet<CashDiscountTerm[]>("/api/v1/cash-discount-terms");
  if (result.ok) cashDiscountTerms.value = result.data.filter((term) => term.is_active);
}
async function createNew() {
  selectedId.value = null;
  Object.assign(form, emptyForm());
  form.details = { ...emptyForm().details };
  form.supplier_number = (await reserveNextNumber("suppliers")) ?? "";
}
function select(item: Supplier) { selectedId.value = item.id; Object.assign(form, { ...item, details: { ...item.details } }); }
async function save() {
  const payload = {
    ...form,
    standard_discount_percent: decimalString(form.standard_discount_percent)
  };
  const result = selectedId.value
    ? await apiPut<Supplier>(`/api/v1/suppliers/${selectedId.value}`, payload)
    : await apiPost<Supplier>("/api/v1/suppliers", payload);
  status.value = result.ok ? "Lieferant gespeichert." : result.message; kind.value = result.ok ? "success" : "error";
  if (result.ok) { selectedId.value = result.data.id; await load(); }
}
async function deactivate() {
  if (!selectedId.value) return;
  const result = await apiDelete(`/api/v1/suppliers/${selectedId.value}`);
  status.value = result.ok ? "Lieferant deaktiviert." : result.message; kind.value = result.ok ? "success" : "error";
  if (result.ok) await load();
}
onMounted(async () => {
  await Promise.all([load(), loadCashDiscountTerms()]);
});
watch(() => liveUpdateState.revision, () => Promise.all([load(), loadCashDiscountTerms()]));
</script>
<template>
  <PageHeader title="Lieferanten" description="Lieferantenstamm und Zahlungskonditionen." />
  <div class="workspace-split">
    <section class="panel list-panel">
      <div class="section-title"><h2>Lieferanten</h2><button type="button" @click="createNew">Neu</button></div>
      <label class="field list-search"><span>Suche</span><input v-model="search" type="search" placeholder="Lieferantennummer oder Name" /></label>
      <button v-for="item in filteredSuppliers" :key="item.id" type="button" class="list-row" :class="{ selected: selectedId === item.id }" @click="select(item)">
        <strong>{{ item.supplier_number }}</strong><span>{{ item.name }}</span><small>{{ item.status }}</small>
      </button>
      <p v-if="suppliers.length === 0" class="empty">Keine Lieferanten vorhanden.</p>
      <p v-else-if="filteredSuppliers.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>Lieferantennummer</span><div class="readonly-value">{{ form.supplier_number || "wird automatisch vergeben" }}</div></label>
          <label class="field"><span>Name</span><input v-model="form.name" required /></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>
          <label class="field"><span>Rabatt %</span><input v-model="form.standard_discount_percent" inputmode="decimal" /></label>
          <label class="field">
            <span>Skonto-Regel</span>
            <select v-model="form.cash_discount_term_id">
              <option :value="null">Keine</option>
              <option v-for="term in cashDiscountTerms" :key="term.id" :value="term.id">{{ term.code }} - {{ term.name }}</option>
            </select>
          </label>
          <label class="field"><span>Zahlungsziel Tage</span><input v-model="form.payment_days" type="number" min="0" /></label>
          <label class="field"><span>Straße</span><input v-model="form.details.street" /></label>
          <label class="field"><span>PLZ</span><input v-model="form.details.postal_code" /></label>
          <label class="field"><span>Ort</span><input v-model="form.details.city" /></label>
          <label class="field"><span>E-Mail</span><input v-model="form.details.email" type="email" /></label>
          <label class="field"><span>Telefon</span><input v-model="form.details.phone" /></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>
    </section>
  </div>
</template>
