<script setup lang="ts">
type Instance = {
  id: string;
  instanceId: string;
  name: string;
  baseUrl: string;
  status: "active" | "blocked" | "disabled";
  mode: "minimal" | "rich";
  capabilities: string[];
  currentSecretPreview: string;
  nextSecretPreview?: string | null;
  lastHeartbeatAt?: string | null;
};

const pushApi = usePushApi();
const toast = useToast();
const createOpen = ref(false);
const createdSecret = ref("");
const form = reactive({
  name: "",
  baseUrl: "",
  mode: "minimal",
  capabilities: "ios_push,minimal_payload",
});

const { data: instances, pending, refresh } = await useAsyncData("instances", () => pushApi.request<Instance[]>("/admin/instances"), {
  default: () => [],
  immediate: false,
});

onMounted(async () => {
  pushApi.hydrateToken();
  if (pushApi.token.value) await refresh();
});

async function createInstance() {
  const created = await pushApi.request<Instance & { clientSecret: string }>("/admin/instances", {
    method: "POST",
    body: {
      name: form.name,
      baseUrl: form.baseUrl,
      mode: form.mode,
      capabilities: form.capabilities.split(",").map((item) => item.trim()).filter(Boolean),
    },
  });
  createdSecret.value = created.clientSecret;
  createOpen.value = false;
  form.name = "";
  form.baseUrl = "";
  await refresh();
  toast.add({ title: "Instanz angelegt", color: "success" });
}

async function patchInstance(instance: Instance, status: Instance["status"]) {
  await pushApi.request(`/admin/instances/${instance.id}`, {
    method: "PATCH",
    body: { status },
  });
  await refresh();
}

async function rotateSecret(instance: Instance) {
  const result = await pushApi.request<Instance & { nextClientSecret: string }>(`/admin/instances/${instance.id}/rotate-secret`, {
    method: "POST",
    body: {},
  });
  createdSecret.value = result.nextClientSecret;
  await refresh();
}
</script>

<template>
  <AdminShell>
    <TokenGate>
      <div class="space-y-6">
        <div class="flex flex-wrap items-center justify-between gap-3">
          <div>
            <h2 class="text-2xl font-bold text-gray-950">Instanzen</h2>
            <p class="text-sm text-gray-500">Selfhosted FEDEO-Instanzen und ihre Gateway-Schlüssel.</p>
          </div>
          <div class="flex gap-2">
            <UButton icon="i-lucide-refresh-cw" variant="soft" :loading="pending" @click="refresh()">Aktualisieren</UButton>
            <UButton icon="i-lucide-plus" @click="createOpen = true">Instanz</UButton>
          </div>
        </div>

        <UAlert
          v-if="createdSecret"
          color="warning"
          icon="i-lucide-key-round"
          title="Schlüssel nur jetzt kopieren"
          :description="createdSecret"
        />

        <div class="grid gap-4">
          <UCard v-for="instance in instances" :key="instance.id">
            <div class="flex flex-wrap items-start justify-between gap-4">
              <div class="min-w-0">
                <div class="flex items-center gap-2">
                  <h3 class="truncate text-lg font-bold">{{ instance.name }}</h3>
                  <UBadge :color="instance.status === 'active' ? 'success' : instance.status === 'blocked' ? 'error' : 'neutral'" variant="soft">
                    {{ instance.status }}
                  </UBadge>
                </div>
                <p class="mt-1 text-sm text-gray-500">{{ instance.instanceId }}</p>
                <p class="mt-1 text-sm text-gray-700">{{ instance.baseUrl }}</p>
                <div class="mt-3 flex flex-wrap gap-2">
                  <UBadge v-for="capability in instance.capabilities" :key="capability" color="success" variant="subtle">
                    {{ capability }}
                  </UBadge>
                </div>
              </div>
              <div class="flex flex-wrap gap-2">
                <UButton icon="i-lucide-key-round" variant="soft" @click="rotateSecret(instance)">Rotieren</UButton>
                <UButton v-if="instance.status !== 'active'" color="success" variant="soft" @click="patchInstance(instance, 'active')">Aktivieren</UButton>
                <UButton v-else color="error" variant="soft" @click="patchInstance(instance, 'blocked')">Sperren</UButton>
                <UButton icon="i-lucide-arrow-right" variant="ghost" :to="`/instances/${instance.id}`" />
              </div>
            </div>
            <div class="mt-4 grid gap-3 text-sm md:grid-cols-3">
              <div>
                <p class="text-gray-500">Aktueller Schlüssel</p>
                <p class="font-mono">{{ instance.currentSecretPreview }}</p>
              </div>
              <div>
                <p class="text-gray-500">Nächster Schlüssel</p>
                <p class="font-mono">{{ instance.nextSecretPreview || "nicht gesetzt" }}</p>
              </div>
              <div>
                <p class="text-gray-500">Heartbeat</p>
                <p>{{ instance.lastHeartbeatAt ? new Date(instance.lastHeartbeatAt).toLocaleString() : "noch keiner" }}</p>
              </div>
            </div>
          </UCard>
        </div>
      </div>

      <UModal v-model:open="createOpen" title="Instanz anlegen">
        <template #body>
          <form class="space-y-4" @submit.prevent="createInstance">
            <UFormField label="Name">
              <UInput v-model="form.name" placeholder="Kunde / Selfhost-Instanz" />
            </UFormField>
            <UFormField label="Basis-URL">
              <UInput v-model="form.baseUrl" placeholder="https://app.example.com" />
            </UFormField>
            <UFormField label="Payload-Modus">
              <USelect v-model="form.mode" :items="['minimal', 'rich']" />
            </UFormField>
            <UFormField label="Fähigkeiten">
              <UInput v-model="form.capabilities" />
            </UFormField>
            <div class="flex justify-end gap-2">
              <UButton variant="soft" @click="createOpen = false">Abbrechen</UButton>
              <UButton type="submit">Anlegen</UButton>
            </div>
          </form>
        </template>
      </UModal>
    </TokenGate>
  </AdminShell>
</template>
