<script setup lang="ts">
import { computed, onMounted, ref } from "vue";
import { apiKeysAPI } from "@/api";
import EmptyState from "@/components/common/EmptyState.vue";
import PageHeader from "@/components/common/PageHeader.vue";
import type { ApiKeyRecord } from "@/types";

const keys = ref<ApiKeyRecord[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const mutationError = ref<string | null>(null);
const newKeyName = ref("HWLAB CLI key");
const createdSecret = ref<string | null>(null);
const pending = ref<string | null>(null);
const editingId = ref<string | null>(null);
const editingName = ref("");

const activeKeys = computed(() => keys.value.filter((key) => !key.revokedAt));

onMounted(refresh);

async function refresh(): Promise<void> {
  loading.value = true;
  const response = await apiKeysAPI.list();
  keys.value = response.data?.keys ?? [];
  error.value = response.ok ? null : response.error;
  loading.value = false;
}

async function createKey(): Promise<void> {
  pending.value = "create";
  mutationError.value = null;
  createdSecret.value = null;
  const response = await apiKeysAPI.create(newKeyName.value.trim() || "HWLAB API key");
  pending.value = null;
  if (!response.ok) {
    mutationError.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  const payload = response.data ?? {};
  createdSecret.value = payload.secret ?? payload.key?.displaySecret ?? null;
  await refresh();
}

function startRename(key: ApiKeyRecord): void {
  editingId.value = key.id;
  editingName.value = key.name || "";
}

async function saveRename(key: ApiKeyRecord): Promise<void> {
  if (!editingId.value) return;
  pending.value = `rename:${key.id}`;
  mutationError.value = null;
  const response = await apiKeysAPI.rename(key.id, editingName.value.trim() || key.name || key.id);
  pending.value = null;
  if (!response.ok) {
    mutationError.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  editingId.value = null;
  editingName.value = "";
  await refresh();
}

async function revokeKey(key: ApiKeyRecord): Promise<void> {
  if (!window.confirm(`撤销 API key ${key.name || key.id}？`)) return;
  pending.value = `revoke:${key.id}`;
  mutationError.value = null;
  const response = await apiKeysAPI.revoke(key.id);
  pending.value = null;
  if (!response.ok) {
    mutationError.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  await refresh();
}

function formatDate(value: unknown): string {
  const text = String(value ?? "").trim();
  if (!text) return "-";
  const date = new Date(text);
  if (Number.isNaN(date.getTime())) return text;
  return date.toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
}
</script>

<template>
  <section class="route-stack">
    <PageHeader eyebrow="User" title="API Keys" description="API key 供 CLI、AgentRun/HWPOD 调用使用；浏览器请求仍使用 HttpOnly Web session。" />
    <EmptyState v-if="loading" title="正在加载 API keys" description="正在读取当前用户的 user-billing API key。" />
    <EmptyState v-else-if="error" title="API key 接口不可用" :description="error" />
    <template v-else>
      <section class="data-panel api-key-create-panel">
        <header class="panel-header">
          <h2>创建 API key</h2>
          <small>{{ activeKeys.length }} active / {{ keys.length }} total</small>
        </header>
        <div class="inline-form-row">
          <input v-model="newKeyName" class="input" placeholder="API key 名称" />
          <button class="btn btn-primary" type="button" :disabled="pending === 'create'" @click="createKey">{{ pending === "create" ? "创建中" : "创建" }}</button>
        </div>
        <p v-if="mutationError" class="form-error">{{ mutationError }}</p>
        <div v-if="createdSecret" class="secret-once-box">
          <strong>新 key 只显示一次</strong>
          <code>{{ createdSecret }}</code>
          <button class="table-action" type="button" @click="createdSecret = null">已保存</button>
        </div>
      </section>

      <section class="data-panel usage-panel">
        <header class="panel-header">
          <h2>当前 API keys</h2>
          <small>prefix 和时间来自 PK01 user-billing authority</small>
        </header>
        <table v-if="keys.length" class="data-table usage-table api-key-table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Prefix</th>
              <th>Status</th>
              <th>Created</th>
              <th>Last used</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="key in keys" :key="key.id">
              <td>
                <div v-if="editingId === key.id" class="inline-edit-row">
                  <input v-model="editingName" class="input" />
                  <button class="table-action" type="button" :disabled="pending === `rename:${key.id}`" @click="saveRename(key)">保存</button>
                </div>
                <strong v-else>{{ key.name || key.id }}</strong>
                <small>{{ key.id }}</small>
              </td>
              <td><code>{{ key.prefix || "-" }}</code></td>
              <td><span class="status-pill" :data-status="key.revokedAt ? 'disabled' : 'active'">{{ key.revokedAt ? "revoked" : "active" }}</span></td>
              <td>{{ formatDate(key.createdAt) }}</td>
              <td>{{ formatDate(key.lastUsedAt) }}</td>
              <td>
                <button v-if="!key.revokedAt" class="table-action" type="button" @click="startRename(key)">重命名</button>
                <button v-if="!key.revokedAt" class="table-action danger" type="button" :disabled="pending === `revoke:${key.id}`" @click="revokeKey(key)">撤销</button>
              </td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted-box">当前用户还没有 API key。</p>
      </section>
    </template>
  </section>
</template>
