<script setup lang="ts">
import { onMounted, ref } from "vue";
import { apiGet } from "../api";
import PageHeader from "../components/PageHeader.vue";
import type { OrganizationRegistration } from "../types";
import { formatDate } from "../utils";

const registrations = ref<OrganizationRegistration[]>([]);
const status = ref("Noch keine Daten geladen.");
const loaded = ref(false);
const loading = ref(false);

async function load() {
  loading.value = true;
  status.value = "Lade Registrierungen...";
  const result = await apiGet<OrganizationRegistration[]>("/api/v1/admin/organization-registrations");
  loaded.value = true;
  loading.value = false;
  if (!result.ok) {
    registrations.value = [];
    status.value = result.message;
    return;
  }
  registrations.value = result.data;
  status.value = "Keine Registrierungen vorhanden.";
}

onMounted(load);
</script>

<template>
  <PageHeader title="Freischaltungen" description="Offene und entschiedene Organization-Registrierungen." />
  <section class="panel">
    <div class="section-title">
      <h2>Registrierungen</h2>
      <button type="button" :disabled="loading" @click="load">
        {{ loading ? "Lädt..." : "Aktualisieren" }}
      </button>
    </div>
    <p v-if="!loaded || registrations.length === 0" class="empty">{{ status }}</p>
    <div v-else class="data-table registrations">
      <div class="table-head">Firma</div>
      <div class="table-head">E-Mail</div>
      <div class="table-head">Status</div>
      <div class="table-head">Eingegangen</div>
      <template v-for="item in registrations" :key="item.id">
        <RouterLink :to="`/admin/organization-registrations/${encodeURIComponent(item.id)}`">
          {{ item.organization_name ?? item.id }}
        </RouterLink>
        <div>{{ item.email }}</div>
        <span class="status-pill">{{ item.status }}</span>
        <time>{{ formatDate(item.requested_at) }}</time>
      </template>
    </div>
  </section>
</template>
