<script setup lang="ts">
import { ref } from "vue";
import { apiPost } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import type { PriceListImportApplyResponse, PriceListImportPreview } from "../types";

const sourceName = ref("Preisliste.csv");
const delimiter = ref(";");
const content = ref("item_number;name;manufacturer_code;unit;tax_rate;purchase_price;sales_price;supplier_number;supplier_item_number;currency\nAR-IMPORT-1;Importartikel;HERST-001;Stck;19,00;10,00;25,00;LI000000001;EXT-4711;EUR");
const preview = ref<PriceListImportPreview | null>(null);
const status = ref("");
const kind = ref<"info" | "success" | "error">("info");

function payload() {
  return { source_name: sourceName.value, delimiter: delimiter.value, content: content.value };
}

async function runPreview() {
  const result = await apiPost<PriceListImportPreview>("/api/v1/imports/price-list/preview", payload());
  if (result.ok) { preview.value = result.data; status.value = "Vorschau erstellt."; kind.value = "success"; }
  else { status.value = result.message; kind.value = "error"; }
}

async function applyImport() {
  const result = await apiPost<PriceListImportApplyResponse>("/api/v1/imports/price-list/apply", payload());
  if (result.ok) { status.value = `Import ${result.data.import_id}: ${result.data.applied_rows} Zeilen übernommen.`; kind.value = "success"; await runPreview(); }
  else { status.value = result.message; kind.value = "error"; }
}
</script>
<template>
  <PageHeader title="Preislistenimport" description="CSV-Preislisten prüfen und Artikelpreise historisiert übernehmen." />
  <section class="panel">
    <div class="form-grid">
      <label class="field"><span>Quelle</span><input v-model="sourceName" /></label>
      <label class="field"><span>Trennzeichen</span><input v-model="delimiter" /></label>
      <label class="field full-width"><span>CSV-Inhalt</span><textarea v-model="content" rows="10" /></label>
    </div>
    <div class="form-actions"><button type="button" @click="runPreview">Vorschau</button><button type="button" @click="applyImport">Importieren</button></div>
    <FormStatus :message="status" :kind="kind" />
  </section>
  <section v-if="preview" class="panel">
    <div class="section-title"><h2>Vorschau</h2><span>{{ preview.valid_rows }} gültig, {{ preview.error_rows }} Fehler</span></div>
    <div v-for="row in preview.rows" :key="row.row_number" class="data-row">
      <strong>{{ row.row_number }} {{ row.action }}</strong>
      <span>{{ row.item_number }}</span>
      <span>{{ row.name }}</span>
      <span>{{ row.manufacturer_code ?? "-" }}</span>
      <span>{{ row.supplier_number ? `${row.supplier_number} / ${row.supplier_item_number}` : "-" }}</span>
      <small>{{ row.error ?? `${row.purchase_price ?? "-"} ${row.currency ?? "EUR"} / ${row.sales_price ?? "-"}` }}</small>
    </div>
  </section>
</template>
