<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { apiGet, apiPut } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import { liveUpdateState } from "../realtime";
import type { NumberRange } from "../types";

const labels: Record<string, string> = {
  items: "Artikel",
  activities: "Aktivitäten",
  outgoing_invoices: "Rechnungen",
  incoming_invoices: "Eingangsrechnungen",
  customers: "Kunden",
  suppliers: "Lieferanten",
  quotes: "Angebote"
};

const ranges = ref<NumberRange[]>([]);
const selectedCode = ref<string | null>(null);
const form = reactive({
  pattern: "",
  counter_value: 0,
  counter_padding: 9,
  reset_rule: null as string | null,
  is_active: true
});
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");

async function load() {
  const result = await apiGet<NumberRange[]>("/api/v1/number-ranges");
  if (!result.ok) {
    status.value = result.message;
    kind.value = "error";
    return;
  }
  ranges.value = result.data;
  if (!selectedCode.value && ranges.value[0]) select(ranges.value[0]);
}

function select(range: NumberRange) {
  selectedCode.value = range.code;
  Object.assign(form, {
    pattern: range.pattern,
    counter_value: range.counter_value,
    counter_padding: range.counter_padding,
    reset_rule: range.reset_rule ?? null,
    is_active: range.is_active
  });
}

async function save() {
  if (!selectedCode.value) return;
  const result = await apiPut<NumberRange>(`/api/v1/number-ranges/${selectedCode.value}`, form);
  status.value = result.ok ? "Nummernkreis gespeichert." : result.message;
  kind.value = result.ok ? "success" : "error";
  if (result.ok) await load();
}

onMounted(load);
watch(() => liveUpdateState.revision, load);
</script>

<template>
  <PageHeader title="Nummernkreise" description="Individuelle Nummern für Stammdaten, Angebote und Rechnungen." />
  <div class="workspace-split">
    <section class="panel list-panel">
      <h2>Bereiche</h2>
      <button v-for="range in ranges" :key="range.code" type="button" class="list-row" :class="{ selected: selectedCode === range.code }" @click="select(range)">
        <strong>{{ labels[range.code] ?? range.code }}</strong>
        <span>{{ range.pattern }}</span>
        <small>Zähler {{ range.counter_value }}</small>
      </button>
    </section>
    <section class="panel detail-panel">
      <form @submit.prevent="save">
        <div class="form-grid">
          <label class="field"><span>Muster</span><input v-model="form.pattern" required /></label>
          <label class="field"><span>Zählerstand</span><input v-model="form.counter_value" type="number" min="0" required /></label>
          <label class="field"><span>Zählerlänge</span><input v-model="form.counter_padding" type="number" min="1" max="18" required /></label>
          <label class="field"><span>Reset-Regel</span><input v-model="form.reset_rule" /></label>
          <label class="check-row"><input v-model="form.is_active" type="checkbox" /><span>Aktiv</span></label>
        </div>
        <p class="muted">Das Muster muss <code>{counter}</code> enthalten. Der Zähler wird bei 9 Stellen als 000.000.001 formatiert.</p>
        <div class="form-actions"><button type="submit" :disabled="!selectedCode">Speichern</button></div>
        <FormStatus :message="status" :kind="kind" />
      </form>
    </section>
  </div>
</template>
