<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import { apiGet, apiPost } from "../api";
import FormStatus from "../components/FormStatus.vue";
import PageHeader from "../components/PageHeader.vue";
import type { OrganizationRegistrationDetail } from "../types";
import { formatDate } from "../utils";

const route = useRoute();
const detail = ref<OrganizationRegistrationDetail | null>(null);
const emptyMessage = ref("Details noch nicht geladen.");
const status = ref("");
const statusKind = ref<"info" | "success" | "error">("info");

const id = String(route.params.id ?? "");

onMounted(load);

async function load() {
  const result = await apiGet<OrganizationRegistrationDetail>(`/api/v1/admin/organization-registrations/${encodeURIComponent(id)}`);
  if (!result.ok) {
    detail.value = null;
    emptyMessage.value = result.message;
    return;
  }
  detail.value = result.data;
}

async function runAction(action: "approve" | "reject" | "resend-initial-email" | "retry-provisioning") {
  const result = await apiPost(`/api/v1/admin/organization-registrations/${encodeURIComponent(id)}/${action}`, {});
  status.value = result.ok ? "Aktion ausgeführt." : result.message;
  statusKind.value = result.ok ? "success" : "error";
  if (result.ok) await load();
}
</script>

<template>
  <PageHeader title="Registrierungsdetail" description="Prüfen, freischalten oder ablehnen." />
  <section class="panel">
    <div class="section-title">
      <h2>Details</h2>
      <button type="button" @click="load">Laden</button>
    </div>
    <p v-if="!detail" class="empty">{{ emptyMessage }}</p>
    <dl v-else class="detail-grid">
      <dt>Firma</dt><dd>{{ detail.organization_name ?? "-" }}</dd>
      <dt>E-Mail</dt><dd>{{ detail.email }}</dd>
      <dt>Status</dt><dd>{{ detail.status }}</dd>
      <dt>Organization-ID</dt><dd><code>{{ detail.organization_id ?? "-" }}</code></dd>
      <dt>Schema</dt><dd><code>{{ detail.schema_name ?? "-" }}</code></dd>
      <dt>Angefragt</dt><dd>{{ formatDate(detail.requested_at) }}</dd>
      <dt>Entschieden</dt><dd>{{ formatDate(detail.decided_at) }}</dd>
      <dt>Provisioning</dt><dd>{{ detail.provisioning_error ?? "-" }}</dd>
    </dl>
    <div class="button-row">
      <button type="button" @click="runAction('approve')">Freischalten</button>
      <button type="button" class="secondary" @click="runAction('reject')">Ablehnen</button>
      <button type="button" class="secondary" @click="runAction('resend-initial-email')">E-Mail erneut senden</button>
      <button type="button" class="secondary" @click="runAction('retry-provisioning')">Schema-Erstellung wiederholen</button>
    </div>
    <FormStatus :message="status" :kind="statusKind" />
  </section>
</template>
