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

const summary = ref<UsageSummary | null>(null);
const loading = ref(true);
const error = ref<string | null>(null);

const credits = computed(() => summary.value?.credits ?? {});
const usage = computed(() => summary.value?.usage ?? {});
const plan = computed(() => summary.value?.plan ?? {});
const entitlements = computed(() => summary.value?.entitlements ?? []);
const services = computed(() => usage.value.byService ?? []);
const ledgerRows = computed(() => summary.value?.ledger?.rows ?? []);
const reservations = computed(() => summary.value?.reservations?.active ?? []);

onMounted(async () => {
  loading.value = true;
  const response = await usageAPI.summary();
  if (!response.ok) {
    error.value = response.error ?? `HTTP ${response.status}`;
    summary.value = null;
  } else {
    summary.value = response.data;
    error.value = null;
  }
  loading.value = false;
});

function formatNumber(value: unknown): string {
  const number = Number(value ?? 0);
  if (!Number.isFinite(number)) return "0";
  return new Intl.NumberFormat("zh-CN").format(number);
}

function formatSignedCredits(value: unknown): string {
  const number = Number(value ?? 0);
  const sign = number > 0 ? "+" : "";
  return `${sign}${formatNumber(number)}`;
}

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="用量与配额" description="PK01 PostgreSQL ledger 派生的余额、消费和预留。" />
    <EmptyState v-if="loading" title="正在加载用量" description="正在读取用户账务 summary。" />
    <EmptyState v-else-if="error" title="用量接口不可用" :description="error" />
    <EmptyState v-else-if="!summary" title="暂无用量数据" description="当前账号还没有账务 summary。" />
    <template v-else>
      <div class="overview-grid usage-metrics">
        <article class="metric-card">
          <span>Plan</span>
          <strong>{{ plan.displayName || summary.planId || "default" }}</strong>
        </article>
        <article class="metric-card">
          <span>可用 credit</span>
          <strong>{{ formatNumber(credits.available) }}</strong>
        </article>
        <article class="metric-card">
          <span>余额</span>
          <strong>{{ formatNumber(credits.balance) }}</strong>
        </article>
        <article class="metric-card">
          <span>已预留</span>
          <strong>{{ formatNumber(credits.reserved) }}</strong>
        </article>
      </div>

      <section class="data-panel usage-panel">
        <header class="panel-header">
          <h2>资源授权</h2>
          <small>{{ entitlements.length }} resources / {{ plan.status || "active" }}</small>
        </header>
        <table v-if="entitlements.length" class="data-table usage-table">
          <thead>
            <tr>
              <th>Resource</th>
              <th>Status</th>
              <th>Monthly</th>
              <th>Concurrent</th>
              <th>RPM</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in entitlements" :key="item.resourceType">
              <td><code>{{ item.resourceType }}</code></td>
              <td><span class="status-pill" :data-status="item.enabled ? 'active' : 'disabled'">{{ item.enabled ? "enabled" : "disabled" }}</span></td>
              <td>{{ formatNumber(item.monthlyUsageCredits) }} / {{ item.monthlyQuotaUnlimited ? "unlimited" : formatNumber(item.monthlyQuotaCredits) }}</td>
              <td>{{ formatNumber(item.activeReservations) }} / {{ item.concurrencyUnlimited ? "unlimited" : formatNumber(item.maxConcurrentReservations) }}</td>
              <td>{{ formatNumber(item.rpmUsed) }} / {{ item.rpmUnlimited ? "unlimited" : formatNumber(item.rpmLimit) }}</td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted-box">当前 plan 没有资源授权记录。</p>
      </section>

      <div class="usage-panels">
        <section class="data-panel usage-panel">
          <header class="panel-header">
            <h2>服务用量</h2>
            <small>{{ formatNumber(usage.recordCount) }} records / {{ formatNumber(usage.totalCredits) }} credits</small>
          </header>
          <table v-if="services.length" class="data-table usage-table">
            <thead>
              <tr>
                <th>Service</th>
                <th>Resource</th>
                <th>Credits</th>
                <th>Quantity</th>
                <th>Records</th>
                <th>Last used</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in services" :key="item.serviceId">
                <td><code>{{ item.serviceId }}</code></td>
                <td><code>{{ item.resourceType || "generic" }}</code></td>
                <td>{{ formatNumber(item.credits) }}</td>
                <td>{{ formatNumber(item.quantity) }}</td>
                <td>{{ formatNumber(item.recordCount) }}</td>
                <td>{{ formatDate(item.lastUsedAt) }}</td>
              </tr>
            </tbody>
          </table>
          <p v-else class="muted-box">暂无服务消费记录。</p>
        </section>

        <section class="data-panel usage-panel">
          <header class="panel-header">
            <h2>最近账务</h2>
            <small>{{ formatNumber(summary.ledger?.count) }} rows</small>
          </header>
          <table v-if="ledgerRows.length" class="data-table usage-table">
            <thead>
              <tr>
                <th>Time</th>
                <th>Kind</th>
                <th>Reason</th>
                <th>Delta</th>
                <th>Balance</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="row in ledgerRows" :key="row.id">
                <td>{{ formatDate(row.createdAt) }}</td>
                <td>{{ row.kind }}</td>
                <td><code>{{ row.reason }}</code></td>
                <td>{{ formatSignedCredits(row.deltaCredits) }}</td>
                <td>{{ formatNumber(row.balanceAfter) }}</td>
              </tr>
            </tbody>
          </table>
          <p v-else class="muted-box">暂无 ledger 记录。</p>
        </section>
      </div>

      <section class="data-panel usage-panel">
        <header class="panel-header">
          <h2>Active reservations</h2>
          <small>{{ formatNumber(summary.reservations?.activeCount) }} reserved</small>
        </header>
        <table v-if="reservations.length" class="data-table usage-table">
          <thead>
            <tr>
              <th>Reservation</th>
              <th>Service</th>
              <th>Resource</th>
              <th>Credits</th>
              <th>Expires</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in reservations" :key="item.reservationId">
              <td><code>{{ item.reservationId }}</code></td>
              <td><code>{{ item.serviceId }}</code></td>
              <td><code>{{ item.resourceType || "generic" }}</code></td>
              <td>{{ formatNumber(item.estimatedCredits) }}</td>
              <td>{{ formatDate(item.expiresAt) }}</td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted-box">当前没有 active reservation。</p>
      </section>
    </template>
  </section>
</template>
