<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 { decimalString, normalizeTaxRate, taxRateOptions } from "../format";
import { reserveNextNumber } from "../number-ranges";
import { liveUpdateState } from "../realtime";
import type { Activity, Customer, Item, Quote, QuoteItem } from "../types";

const emptyItem = (): QuoteItem => ({ line_kind: "item", item_id: "", activity_id: null, description: "", quantity: "1", unit_price: "0", original_unit_price: null, discount_percent: "0", tax_rate: "19" });
const emptyForm = () => ({ quote_number: "", customer_id: "", status: "draft", valid_until: null as string | null, cash_discount_term_id: null as string | null, customer_discount_percent: "0", notes: "", items: [emptyItem()] });

const quotes = ref<Quote[]>([]);
const customers = ref<Customer[]>([]);
const items = ref<Item[]>([]);
const activities = ref<Activity[]>([]);
const selectedId = ref<string | null>(null);
const form = reactive(emptyForm());
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");
const selectedQuote = computed(() => quotes.value.find((quote) => quote.id === selectedId.value));
const search = ref("");
const editingLineIndex = ref(0);
const customerName = (customerId: string) => customers.value.find((customer) => customer.id === customerId)?.name ?? customerId;
const filteredQuotes = computed(() => {
  const needle = search.value.trim().toLowerCase();
  if (!needle) return quotes.value;
  return quotes.value.filter((quote) =>
    `${quote.quote_number} ${customerName(quote.customer_id)} ${quote.status}`.toLowerCase().includes(needle)
  );
});

async function load() {
  const [quoteResult, customerResult, itemResult, activityResult] = await Promise.all([
    apiGet<Quote[]>("/api/v1/quotes"),
    apiGet<Customer[]>("/api/v1/customers"),
    apiGet<Item[]>("/api/v1/items"),
    apiGet<Activity[]>("/api/v1/activities")
  ]);
  if (quoteResult.ok) quotes.value = quoteResult.data; else { status.value = quoteResult.message; kind.value = "error"; }
  if (customerResult.ok) customers.value = customerResult.data.filter((customer) => customer.status === "active");
  if (itemResult.ok) items.value = itemResult.data.filter((item) => item.status === "active");
  if (activityResult.ok) activities.value = activityResult.data.filter((activity) => activity.status === "active");
}

async function createNew() {
  selectedId.value = null;
  Object.assign(form, emptyForm());
  editingLineIndex.value = 0;
  form.quote_number = (await reserveNextNumber("quotes")) ?? "";
}

function select(quote: Quote) {
  selectedId.value = quote.id;
  Object.assign(form, { ...quote, items: quote.items.map((item) => ({ ...item, line_kind: item.line_kind ?? "item", tax_rate: normalizeTaxRate(item.tax_rate) })) });
  editingLineIndex.value = 0;
}

function addLine() {
  form.items.push(emptyItem());
  editingLineIndex.value = form.items.length - 1;
}

function removeLine(index: number) {
  if (form.items.length > 1) form.items.splice(index, 1);
  editingLineIndex.value = Math.min(editingLineIndex.value, form.items.length - 1);
}

function applyItemDefaults(line: QuoteItem) {
  const item = items.value.find((record) => record.id === line.item_id);
  if (!item) return;
  line.description = item.name;
  line.unit_price = item.default_sales_price ?? "0";
  line.original_unit_price = item.default_sales_price ?? null;
  line.tax_rate = normalizeTaxRate(item.tax_rate);
}

const lineSourceOptions = computed(() => [
  ...items.value.map((item) => ({ id: `item:${item.id}`, number: item.item_number, name: item.name })),
  ...activities.value.map((activity) => ({ id: `activity:${activity.id}`, number: activity.activity_number, name: activity.title }))
]);

function lineSourceValue(line: QuoteItem) {
  return line.line_kind === "activity" ? `activity:${line.activity_id ?? ""}` : `item:${line.item_id ?? ""}`;
}

function selectLineSource(line: QuoteItem, value: string | null) {
  if (!value) return;
  const [kind, id] = value.split(":");
  if (kind === "activity") {
    const activity = activities.value.find((record) => record.id === id);
    if (!activity) return;
    line.line_kind = "activity";
    line.activity_id = id;
    line.item_id = null;
    line.description = activity.title;
    line.unit_price = "0";
    line.original_unit_price = null;
    line.tax_rate = "19";
    return;
  }
  const item = items.value.find((record) => record.id === id);
  if (!item) return;
  line.line_kind = "item";
  line.item_id = id;
  line.activity_id = null;
  applyItemDefaults(line);
}

function applyCustomerDefaults(customerId: string | null) {
  if (!customerId) return;
  const customer = customers.value.find((record) => record.id === customerId);
  if (!customer) return;
  form.customer_discount_percent = customer.standard_discount_percent || "0";
  form.cash_discount_term_id = customer.cash_discount_term_id ?? null;
}

function lineName(line: QuoteItem) {
  if (line.line_kind === "activity") {
    const activity = activities.value.find((record) => record.id === line.activity_id);
    return activity ? `${activity.activity_number ?? "Aktivität"} - ${activity.title}` : "Keine Aktivität gewählt";
  }
  if (!line.item_id) return "Kein Artikel gewählt";
  const item = items.value.find((record) => record.id === line.item_id);
  return item ? `${item.item_number} - ${item.name}` : line.item_id;
}

function lineTotal(line: QuoteItem) {
  const quantity = Number(decimalString(line.quantity, "0"));
  const unitPrice = Number(decimalString(line.unit_price, "0"));
  const discount = Number(decimalString(line.discount_percent, "0"));
  const total = quantity * unitPrice * (1 - discount / 100);
  return Number.isFinite(total) ? total.toLocaleString("de-DE", { minimumFractionDigits: 2, maximumFractionDigits: 4 }) : "-";
}

async function save() {
  const payload = {
    ...form,
    customer_discount_percent: decimalString(form.customer_discount_percent),
    items: form.items.map((item) => ({
      ...item,
      line_kind: item.line_kind ?? "item",
      item_id: item.line_kind === "activity" ? null : item.item_id,
      activity_id: item.line_kind === "activity" ? item.activity_id : null,
      quantity: decimalString(item.quantity, "1"),
      unit_price: decimalString(item.unit_price),
      original_unit_price: item.original_unit_price === null ? null : decimalString(item.original_unit_price),
      discount_percent: decimalString(item.discount_percent),
      tax_rate: normalizeTaxRate(item.tax_rate)
    }))
  };
  const result = selectedId.value
    ? await apiPut<Quote>(`/api/v1/quotes/${selectedId.value}`, payload)
    : await apiPost<Quote>("/api/v1/quotes", payload);
  status.value = result.ok ? "Angebot gespeichert." : result.message;
  kind.value = result.ok ? "success" : "error";
  if (result.ok) { selectedId.value = result.data.id; await load(); }
}

async function cancelQuote() {
  if (!selectedId.value) return;
  const result = await apiDelete(`/api/v1/quotes/${selectedId.value}`);
  status.value = result.ok ? "Angebot storniert." : result.message;
  kind.value = result.ok ? "success" : "error";
  if (result.ok) await load();
}

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

<template>
  <PageHeader title="Angebote" description="Angebote mit festen Artikelpositionen und individuellen Preisen." />
  <div class="workspace-split">
    <section class="panel list-panel">
      <div class="section-title"><h2>Angebote</h2><button type="button" @click="createNew">Neu</button></div>
      <label class="field list-search"><span>Suche</span><input v-model="search" type="search" placeholder="Angebotsnummer, Kunde oder Status" /></label>
      <button v-for="quote in filteredQuotes" :key="quote.id" type="button" class="list-row" :class="{ selected: selectedId === quote.id }" @click="select(quote)">
        <strong>{{ quote.quote_number }}</strong>
        <span>{{ customerName(quote.customer_id) }}</span>
        <small>{{ quote.status }}</small>
      </button>
      <p v-if="quotes.length === 0" class="empty">Keine Angebote vorhanden.</p>
      <p v-else-if="filteredQuotes.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>Angebotsnummer</span><div class="readonly-value">{{ form.quote_number || "wird automatisch vergeben" }}</div></label>
          <label class="field"><span>Kunde</span><SearchSelect v-model="form.customer_id" :options="customers.map((customer) => ({ id: customer.id, number: customer.customer_number, name: customer.name }))" placeholder="Kunden-Nr. oder Name suchen" required @change="applyCustomerDefaults" /></label>
          <label class="field"><span>Status</span><select v-model="form.status"><option value="draft">Entwurf</option><option value="sent">Gesendet</option><option value="accepted">Angenommen</option><option value="rejected">Abgelehnt</option><option value="expired">Abgelaufen</option><option value="cancelled">Storniert</option></select></label>
          <label class="field"><span>Gültig bis</span><input v-model="form.valid_until" type="date" /></label>
          <label class="field"><span>Kundenrabatt %</span><input v-model="form.customer_discount_percent" inputmode="decimal" /></label>
          <label class="field full-width"><span>Notizen</span><textarea v-model="form.notes" rows="3" /></label>
        </div>
        <div class="sub-panel">
          <div class="section-title"><h2>Positionen</h2></div>
          <div class="position-table-header"><span>Position</span><span>Menge</span><span>Einzelpreis</span><span>Gesamtpreis</span><span>Steuer</span><span>Aktion</span></div>
          <div v-for="(line, index) in form.items" :key="index" class="quote-line">
            <template v-if="editingLineIndex !== index">
              <div class="position-summary">
                <strong>{{ lineName(line) }}</strong>
                <span>{{ line.quantity }}</span>
                <span>{{ line.unit_price }}</span>
                <span>{{ lineTotal(line) }}</span>
                <span>{{ line.tax_rate }} %</span>
              </div>
              <button type="button" class="secondary" @click="editingLineIndex = index">Bearbeiten</button>
            </template>
            <template v-else>
              <label class="field full-width"><span>Artikel oder Aktivität</span><SearchSelect :model-value="lineSourceValue(line)" :options="lineSourceOptions" placeholder="Artikel-/Aktivitäts-Nr. oder Name suchen" required @change="selectLineSource(line, $event)" /></label>
              <label class="field"><span>Menge</span><input v-model="line.quantity" inputmode="decimal" required /></label>
              <label class="field"><span>Preis</span><input v-model="line.unit_price" inputmode="decimal" required /></label>
              <label class="field"><span>Rabatt %</span><input v-model="line.discount_percent" inputmode="decimal" /></label>
              <label class="field"><span>Steuer %</span><select v-model="line.tax_rate"><option v-for="rate in taxRateOptions" :key="rate" :value="rate">{{ rate }} %</option></select></label>
              <label class="field full-width"><span>Beschreibung</span><input v-model="line.description" /></label>
              <div class="position-actions">
                <button type="button" class="secondary" @click="removeLine(index)">Entfernen</button>
                <button type="button" @click="addLine">Position hinzufügen</button>
              </div>
            </template>
          </div>
        </div>
        <div class="form-actions"><button type="submit">Speichern</button><button v-if="selectedQuote" type="button" class="secondary" @click="cancelQuote">Stornieren</button></div>
        <FormStatus :message="status" :kind="kind" />
      </form>
    </section>
  </div>
</template>
