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

const loading = ref(true);
const error = ref<string | null>(null);
const pending = ref(false);
const redeemError = ref<string | null>(null);
const redeemResult = ref<RedeemResponse | null>(null);
const summary = ref<UsageSummary | null>(null);
const subscription = ref<SubscriptionSummaryResponse | null>(null);
const payment = ref<PaymentSummaryResponse | null>(null);
const form = reactive({ code: "", idempotencyKey: "" });

const credits = computed(() => summary.value?.credits ?? {});
const entitlements = computed(() => subscription.value?.entitlements ?? summary.value?.entitlements ?? []);
const paymentProvider = computed(() => payment.value?.provider ?? subscription.value?.payment ?? {});

onMounted(refreshAll);

async function refreshAll(): Promise<void> {
  loading.value = true;
  const [usage, subs, pay] = await Promise.all([usageAPI.summary(), billingAPI.subscriptionSummary(), billingAPI.paymentSummary()]);
  summary.value = usage.ok ? usage.data : null;
  subscription.value = subs.ok ? subs.data : null;
  payment.value = pay.ok ? pay.data : null;
  error.value = usage.ok || subs.ok || pay.ok ? null : usage.error ?? subs.error ?? pay.error ?? "账务接口不可用";
  loading.value = false;
}

async function redeem(): Promise<void> {
  pending.value = true;
  redeemError.value = null;
  redeemResult.value = null;
  const response = await billingAPI.redeem({ code: form.code.trim(), idempotencyKey: form.idempotencyKey.trim() || undefined });
  pending.value = false;
  if (!response.ok) {
    redeemError.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  redeemResult.value = response.data;
  form.code = "";
  await refreshAll();
}

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 providerStatus(value: Record<string, unknown>): string {
  return String(value.status ?? (value.configured ? "configured" : "unconfigured"));
}
</script>

<template>
  <section class="route-stack">
    <PageHeader eyebrow="Billing" title="充值与订阅" description="兑换码、订阅计划和支付状态均由 PK01 user-billing authority 返回。" />
    <EmptyState v-if="loading" title="正在加载账务" description="正在读取余额、订阅和支付状态。" />
    <EmptyState v-else-if="error" title="账务接口不可用" :description="error" />
    <template v-else>
      <div class="overview-grid usage-metrics">
        <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>Plan</span><strong>{{ subscription?.plan?.displayName || subscription?.planId || summary?.planId || "default" }}</strong></article>
        <article class="metric-card"><span>Payment</span><strong>{{ providerStatus(paymentProvider) }}</strong></article>
      </div>

      <section class="data-panel billing-redeem-panel">
        <header class="panel-header"><h2>兑换码</h2><small>redeem/manual recharge</small></header>
        <p v-if="redeemError" class="form-error admin-action-error">{{ redeemError }}</p>
        <p v-if="redeemResult?.result" class="muted-box">已兑换 {{ formatNumber(redeemResult.result.creditAmount) }} credits，余额 {{ formatNumber(redeemResult.result.balanceBefore) }} -> {{ formatNumber(redeemResult.result.balanceAfter) }}。</p>
        <div class="form-grid two-col">
          <label class="span-2">Code<input v-model="form.code" class="input" autocomplete="one-time-code" placeholder="hwl_redeem_..." @keyup.enter="redeem" /></label>
          <label class="span-2">Idempotency key<input v-model="form.idempotencyKey" class="input" placeholder="可选；重复提交时防重" /></label>
        </div>
        <button class="btn btn-primary" type="button" :disabled="pending || !form.code.trim()" @click="redeem">{{ pending ? "兑换中" : "兑换" }}</button>
      </section>

      <section class="data-panel">
        <header class="panel-header"><h2>订阅计划</h2><small>{{ subscription?.subscriptions?.length ?? 0 }} records</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 没有 entitlement 记录。</p>
      </section>

      <section class="data-panel">
        <header class="panel-header"><h2>支付 Provider</h2><span class="status-pill" :data-status="providerStatus(paymentProvider)">{{ providerStatus(paymentProvider) }}</span></header>
        <p class="muted-box">{{ paymentProvider.message || "真实支付 provider 尚未配置；当前只能使用兑换码或 admin 手动充值。" }}</p>
      </section>
    </template>
  </section>
</template>
