<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 { decimalString, taxRateOptions } from "../format";
import { liveUpdateState } from "../realtime";

type OrganizationSetupForm = {
  display_name: string;
  legal_form: string;
  street: string;
  postal_code: string;
  city: string;
  country: string;
  vat_id: string;
  email: string;
  phone: string;
  default_tax_rate: string;
  default_payment_days: string;
};

type OrganizationSetupResponse = {
  organization_id: string;
  schema_name: string;
  setup: OrganizationSetupForm | null;
};

const form = reactive<OrganizationSetupForm>({
  display_name: "",
  legal_form: "",
  street: "",
  postal_code: "",
  city: "",
  country: "Deutschland",
  vat_id: "",
  email: "",
  phone: "",
  default_tax_rate: "19",
  default_payment_days: "14"
});
const pending = ref(false);
const status = ref("");
const statusKind = ref<"info" | "success" | "error">("info");
const loaded = ref(false);

async function load() {
  pending.value = true;
  status.value = "Lade Firmendaten...";
  statusKind.value = "info";
  const result = await apiGet<OrganizationSetupResponse>("/api/v1/organizations/current/setup");
  pending.value = false;
  if (!result.ok) {
    status.value = result.message;
    statusKind.value = "error";
    return;
  }

  if (result.data.setup) {
    Object.assign(form, result.data.setup);
    status.value = "Firmendaten geladen.";
    statusKind.value = "info";
    loaded.value = true;
    return;
  }

  status.value = "Noch keine Firmendaten gespeichert.";
  statusKind.value = "info";
  loaded.value = true;
}

async function submit() {
  pending.value = true;
  status.value = "Sende Anfrage...";
  statusKind.value = "info";

  const result = await apiPut("/api/v1/organizations/current/setup", {
    ...form,
    default_tax_rate: decimalString(form.default_tax_rate, "19"),
    default_payment_days: String(form.default_payment_days)
  });
  pending.value = false;
  status.value = result.ok ? "Gespeichert." : result.message;
  statusKind.value = result.ok ? "success" : "error";
}

onMounted(load);
watch(
  () => liveUpdateState.revision,
  () => {
    if (loaded.value) load();
  }
);
</script>

<template>
  <PageHeader title="Firmendaten" description="Stammdaten der aktiven Organization erfassen." />
  <section class="panel form-panel wide">
    <form @submit.prevent="submit">
      <div class="form-grid">
        <label class="field"><span>Firmenname</span><input v-model="form.display_name" type="text" placeholder="Muster GmbH" required /></label>
        <label class="field"><span>Rechtsform</span><input v-model="form.legal_form" type="text" placeholder="GmbH" /></label>
        <label class="field"><span>Straße und Hausnummer</span><input v-model="form.street" type="text" required /></label>
        <label class="field"><span>PLZ</span><input v-model="form.postal_code" type="text" required /></label>
        <label class="field"><span>Ort</span><input v-model="form.city" type="text" required /></label>
        <label class="field"><span>Land</span><input v-model="form.country" type="text" required /></label>
        <label class="field"><span>USt-IdNr.</span><input v-model="form.vat_id" type="text" /></label>
        <label class="field"><span>E-Mail der Firma</span><input v-model="form.email" type="email" placeholder="info@example.com" required /></label>
        <label class="field"><span>Telefon</span><input v-model="form.phone" type="tel" /></label>
        <label class="field"><span>Standard-Steuersatz</span><select v-model="form.default_tax_rate" required><option v-for="rate in taxRateOptions" :key="rate" :value="rate">{{ rate }} %</option></select></label>
        <label class="field"><span>Standard-Zahlungsziel</span><input v-model="form.default_payment_days" inputmode="numeric" required /></label>
      </div>
      <div class="form-actions">
        <button type="submit" :disabled="pending">Firmendaten speichern</button>
        <button type="button" class="secondary" :disabled="pending" @click="load">Neu laden</button>
      </div>
      <FormStatus :message="status" :kind="statusKind" />
    </form>
  </section>
</template>
