<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { billingAPI } from "@/api";
import EmptyState from "@/components/common/EmptyState.vue";
import PageHeader from "@/components/common/PageHeader.vue";
import type { RedeemCodeSummary, RedeemRedemptionSummary } from "@/types";

const codes = ref<RedeemCodeSummary[]>([]);
const redemptions = ref<RedeemRedemptionSummary[]>([]);
const loading = ref(true);
const error = ref<string | null>(null);
const pending = ref<string | null>(null);
const createdCode = ref<string | null>(null);
const filters = reactive({ status: "", userId: "", codeId: "" });
const form = reactive({ displayName: "", creditAmount: 10, reason: "redeem", maxRedemptions: 1, perUserLimit: 1, expiresAt: "" });

onMounted(refreshAll);

async function refreshAll(): Promise<void> {
  loading.value = true;
  await Promise.all([loadCodes(), loadRedemptions()]);
  loading.value = false;
}

async function loadCodes(): Promise<void> {
  const response = await billingAPI.adminRedeemCodes({ limit: 100, status: filters.status });
  if (!response.ok) {
    error.value = response.error ?? `HTTP ${response.status}`;
    codes.value = [];
    return;
  }
  codes.value = response.data?.codes ?? [];
  error.value = null;
}

async function loadRedemptions(): Promise<void> {
  const response = await billingAPI.adminRedeemRedemptions({ limit: 100, userId: filters.userId, codeId: filters.codeId });
  if (response.ok) redemptions.value = response.data?.redemptions ?? [];
}

async function createCode(): Promise<void> {
  pending.value = "create";
  createdCode.value = null;
  error.value = null;
  const body: Record<string, unknown> = { ...form, creditAmount: Number(form.creditAmount), maxRedemptions: Number(form.maxRedemptions), perUserLimit: Number(form.perUserLimit) };
  if (!String(form.expiresAt).trim()) delete body.expiresAt;
  else body.expiresAt = new Date(form.expiresAt).toISOString();
  const response = await billingAPI.createAdminRedeemCode(body);
  pending.value = null;
  if (!response.ok) {
    error.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  createdCode.value = response.data?.redeemCode ?? null;
  form.displayName = "";
  await refreshAll();
}

async function setStatus(codeId: string | undefined, status: string): Promise<void> {
  if (!codeId) return;
  pending.value = `status:${codeId}`;
  const response = await billingAPI.updateAdminRedeemCode(codeId, { status });
  pending.value = null;
  if (!response.ok) {
    error.value = response.error ?? `HTTP ${response.status}`;
    return;
  }
  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 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="Admin" title="兑换与订阅" description="管理员生成兑换码并审计 redemption；真实支付 provider 未配置时只显示 placeholder。" />
    <EmptyState v-if="loading" title="正在加载兑换码" description="正在读取 user-billing redeem admin API。" />
    <template v-else>
      <p v-if="error" class="form-error admin-action-error">{{ error }}</p>
      <section class="data-panel">
        <header class="panel-header"><h2>创建兑换码</h2><small>code 只在创建响应中显示一次</small></header>
        <p v-if="createdCode" class="muted-box">新兑换码：<code>{{ createdCode }}</code></p>
        <div class="form-grid two-col">
          <label>名称<input v-model="form.displayName" class="input" placeholder="Campaign / manual recharge" /></label>
          <label>Credits<input v-model.number="form.creditAmount" class="input" type="number" min="1" /></label>
          <label>原因<input v-model="form.reason" class="input" /></label>
          <label>最大兑换次数<input v-model.number="form.maxRedemptions" class="input" type="number" min="1" /></label>
          <label>每用户限制<input v-model.number="form.perUserLimit" class="input" type="number" min="1" /></label>
          <label>过期时间<input v-model="form.expiresAt" class="input" type="datetime-local" /></label>
        </div>
        <button class="btn btn-primary" type="button" :disabled="pending === 'create'" @click="createCode">{{ pending === "create" ? "创建中" : "创建兑换码" }}</button>
      </section>

      <section class="data-panel">
        <header class="panel-header"><h2>兑换码</h2><small>{{ codes.length }} codes</small></header>
        <div class="admin-users-filters">
          <select v-model="filters.status" class="input" @change="loadCodes"><option value="">全部状态</option><option value="active">active</option><option value="disabled">disabled</option><option value="expired">expired</option></select>
          <button class="btn btn-secondary" type="button" @click="loadCodes">刷新</button>
        </div>
        <table v-if="codes.length" class="data-table usage-table admin-billing-table">
          <thead><tr><th>Code</th><th>Status</th><th>Credits</th><th>Usage</th><th>Expires</th><th>Action</th></tr></thead>
          <tbody>
            <tr v-for="code in codes" :key="code.id">
              <td><code>{{ code.codePrefix }}</code><small>{{ code.displayName || code.id }} / {{ code.reason }}</small></td>
              <td><span class="status-pill" :data-status="code.status">{{ code.status }}</span></td>
              <td>{{ formatNumber(code.creditAmount) }}</td>
              <td>{{ formatNumber(code.redeemedCount) }} / {{ formatNumber(code.maxRedemptions) }}<small>per user {{ formatNumber(code.perUserLimit) }}</small></td>
              <td>{{ formatDate(code.expiresAt) }}</td>
              <td><button class="table-action" type="button" :disabled="pending === `status:${code.id}`" @click="setStatus(code.id, code.status === 'disabled' ? 'active' : 'disabled')">{{ code.status === "disabled" ? "启用" : "禁用" }}</button></td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted-box">没有匹配兑换码。</p>
      </section>

      <section class="data-panel">
        <header class="panel-header"><h2>兑换记录</h2><small>{{ redemptions.length }} rows</small></header>
        <div class="admin-users-filters">
          <input v-model="filters.userId" class="input" placeholder="user id" @keyup.enter="loadRedemptions" />
          <input v-model="filters.codeId" class="input" placeholder="code id" @keyup.enter="loadRedemptions" />
          <button class="btn btn-secondary" type="button" @click="loadRedemptions">过滤</button>
        </div>
        <table v-if="redemptions.length" class="data-table usage-table admin-billing-table">
          <thead><tr><th>Time</th><th>User</th><th>Code</th><th>Credits</th><th>Status</th><th>Ledger</th></tr></thead>
          <tbody>
            <tr v-for="row in redemptions" :key="row.id">
              <td>{{ formatDate(row.createdAt) }}<small>{{ row.id }}</small></td>
              <td><code>{{ row.userId }}</code></td>
              <td><code>{{ row.codePrefix }}</code><small>{{ row.codeId }}</small></td>
              <td>{{ formatNumber(row.creditAmount) }}</td>
              <td><span class="status-pill" :data-status="row.status">{{ row.status }}</span></td>
              <td><code>{{ row.ledgerId || "-" }}</code></td>
            </tr>
          </tbody>
        </table>
        <p v-else class="muted-box">暂无兑换记录。</p>
      </section>
    </template>
  </section>
</template>
