import { prisma } from "@/lib/db";
import { ALL_SCOPES } from "@/lib/api-auth";
import { TokenForm } from "./_form";
import { TokenRow } from "./_row";

export const dynamic = "force-dynamic";

export default async function ApiTokensPage() {
  const tokens = await prisma.apiToken.findMany({
    orderBy: { createdAt: "desc" },
    select: {
      id: true,
      name: true,
      prefix: true,
      scopes: true,
      ipAllowlist: true,
      lastUsedAt: true,
      expiresAt: true,
      revoked: true,
      createdAt: true,
    },
  });

  return (
    <div>
      <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">API Tokens</h1>
      <p className="text-sm text-ink-muted mb-6">
        Sinh token cho agent đăng bài tự động qua REST API. Token chỉ hiện 1 lần ngay sau khi tạo —
        copy ngay.
      </p>

      <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-5 mb-8">
        <h2 className="font-display text-lg font-semibold mb-4">Tạo token mới</h2>
        <TokenForm allScopes={ALL_SCOPES} />
      </div>

      <h2 className="font-display text-lg font-semibold mb-3">Token hiện có</h2>
      {tokens.length === 0 ? (
        <p className="text-sm text-ink-muted">Chưa có token nào.</p>
      ) : (
        <div className="rounded-xl border border-stroke-subtle overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-bg-elevated/60 text-left">
              <tr className="border-b border-stroke-subtle">
                <th className="px-4 py-2.5 font-medium text-ink-muted">Tên</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Prefix</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Scopes</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Sử dụng cuối</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">Hết hạn</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted">TT</th>
                <th className="px-4 py-2.5 font-medium text-ink-muted text-right">Hành động</th>
              </tr>
            </thead>
            <tbody>
              {tokens.map((t) => (
                <TokenRow key={t.id} token={t} />
              ))}
            </tbody>
          </table>
        </div>
      )}

      <div className="mt-8 rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-5 text-sm text-ink-secondary">
        <h3 className="font-display font-semibold text-ink-primary mb-2">Cách dùng</h3>
        <pre className="bg-bg-overlay rounded-lg px-3 py-2 overflow-x-auto text-xs">
{`curl -X POST https://v2.finzone.io.vn/api/v1/articles \\
  -H "Authorization: Bearer fz_live_***" \\
  -H "Content-Type: application/json" \\
  -d '{
    "title": "Bitcoin tăng mạnh hôm nay",
    "content": "# Tóm tắt\\n\\n...",
    "categorySlug": "crypto",
    "status": "published",
    "focusKeyword": "bitcoin"
  }'`}
        </pre>
      </div>
    </div>
  );
}
