import type { Metadata } from "next";
import Link from "next/link";
import { Check, X, Crown, Users as UsersIcon, Banknote, Clock } from "lucide-react";
import { prisma } from "@/lib/db";
import { formatVnd } from "@/lib/billing/plans";
import { ApproveButton, RejectButton } from "./_buttons";

export const metadata: Metadata = {
  title: "Billing — Admin · Tử Vi Số",
  robots: { index: false, follow: false },
};

export default async function AdminBillingPage() {
  // Three queries run in parallel — pending, recent resolved, plan stats
  const [pending, recent, premiumCount, freeCount] = await Promise.all([
    prisma.upgradeRequest.findMany({
      where: { status: "PENDING" },
      orderBy: { createdAt: "asc" },
      include: { user: { select: { id: true, email: true, name: true } } },
    }),
    prisma.upgradeRequest.findMany({
      where: { status: { in: ["APPROVED", "REJECTED", "CANCELLED"] } },
      orderBy: { resolvedAt: "desc" },
      take: 25,
      include: { user: { select: { email: true, name: true } } },
    }),
    prisma.user.count({ where: { plan: "PREMIUM" } }),
    prisma.user.count({ where: { OR: [{ plan: "FREE" }, { plan: null }] } }),
  ]);

  const lifetimeRevenue = await prisma.upgradeRequest
    .aggregate({
      where: { status: "APPROVED" },
      _sum: { amountVnd: true },
    })
    .then((r) => r._sum.amountVnd ?? 0);

  return (
    <div>
      <header className="mb-6 flex flex-wrap items-baseline justify-between gap-3">
        <div>
          <h1 className="font-display text-ink-primary text-2xl font-semibold lg:text-3xl">
            Nâng cấp · Billing
          </h1>
          <p className="text-ink-muted mt-1 text-sm">
            Duyệt yêu cầu nâng cấp Premium và xem doanh thu (mock — chưa nối thanh toán).
          </p>
        </div>
        <Link
          href="/pricing"
          className="text-brand-gold text-xs hover:underline"
          target="_blank"
          rel="noreferrer"
        >
          Xem trang /pricing →
        </Link>
      </header>

      {/* KPI cards */}
      <div className="mb-7 grid gap-4 md:grid-cols-4">
        <Kpi
          label="Đang chờ duyệt"
          value={pending.length.toString()}
          icon={<Clock className="h-4 w-4 text-amber-300" />}
          tone="amber"
        />
        <Kpi
          label="Premium hiện có"
          value={premiumCount.toString()}
          icon={<Crown className="text-brand-gold h-4 w-4" />}
          tone="gold"
        />
        <Kpi
          label="Tài khoản FREE"
          value={freeCount.toString()}
          icon={<UsersIcon className="text-ink-secondary h-4 w-4" />}
        />
        <Kpi
          label="Tổng doanh thu (đã duyệt)"
          value={formatVnd(lifetimeRevenue)}
          icon={<Banknote className="h-4 w-4 text-emerald-300" />}
          tone="emerald"
        />
      </div>

      {/* Pending */}
      <section className="border-stroke-default bg-bg-elevated/40 mb-7 rounded-xl border p-5">
        <h2 className="font-display mb-4 text-lg font-semibold">Yêu cầu đang chờ</h2>
        {pending.length === 0 ? (
          <p className="text-ink-muted text-sm">Không có yêu cầu mới.</p>
        ) : (
          <ul className="divide-stroke-subtle/60 divide-y">
            {pending.map((r) => (
              <li key={r.id} className="flex flex-wrap items-baseline gap-3 py-3">
                <div className="min-w-0 grow">
                  <div className="text-ink-primary text-sm font-medium">
                    {r.user.name || r.user.email}{" "}
                    <span className="text-ink-muted text-xs">· {r.user.email}</span>
                  </div>
                  <div className="text-ink-muted text-xs">
                    {new Date(r.createdAt).toLocaleString("vi-VN")} · gói {r.targetPlan} ·{" "}
                    {formatVnd(r.amountVnd ?? 0)}
                  </div>
                  {r.contact ? (
                    <div className="text-ink-secondary text-xs">📞 {r.contact}</div>
                  ) : null}
                  {r.note ? (
                    <div className="text-ink-secondary text-xs italic">&ldquo;{r.note}&rdquo;</div>
                  ) : null}
                </div>
                <div className="flex gap-2">
                  <ApproveButton requestId={r.id} />
                  <RejectButton requestId={r.id} />
                </div>
              </li>
            ))}
          </ul>
        )}
      </section>

      {/* History */}
      <section className="border-stroke-default bg-bg-elevated/40 rounded-xl border p-5">
        <h2 className="font-display mb-4 text-lg font-semibold">25 yêu cầu gần nhất</h2>
        {recent.length === 0 ? (
          <p className="text-ink-muted text-sm">Chưa có lịch sử.</p>
        ) : (
          <ul className="divide-stroke-subtle/60 divide-y text-sm">
            {recent.map((r) => (
              <li key={r.id} className="flex flex-wrap items-baseline gap-3 py-2">
                <span
                  className={
                    r.status === "APPROVED"
                      ? "rounded bg-emerald-500/15 px-2 py-0.5 text-xs text-emerald-300"
                      : r.status === "REJECTED"
                        ? "rounded bg-rose-500/15 px-2 py-0.5 text-xs text-rose-300"
                        : "bg-bg-overlay/60 text-ink-muted rounded px-2 py-0.5 text-xs"
                  }
                >
                  {r.status === "APPROVED" ? (
                    <Check className="mr-1 inline h-3 w-3" />
                  ) : r.status === "REJECTED" ? (
                    <X className="mr-1 inline h-3 w-3" />
                  ) : null}
                  {r.status}
                </span>
                <span className="text-ink-primary text-sm">{r.user.name || r.user.email}</span>
                <span className="text-ink-muted text-xs">{r.user.email}</span>
                <span className="text-ink-muted ml-auto text-xs">
                  {r.resolvedAt ? new Date(r.resolvedAt).toLocaleString("vi-VN") : "?"}
                </span>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}

function Kpi({
  label,
  value,
  icon,
  tone,
}: {
  label: string;
  value: string;
  icon: React.ReactNode;
  tone?: "amber" | "gold" | "emerald";
}) {
  const ring =
    tone === "amber"
      ? "border-amber-500/30 bg-amber-500/5"
      : tone === "gold"
        ? "border-brand-gold/30 bg-brand-gold/5"
        : tone === "emerald"
          ? "border-emerald-500/30 bg-emerald-500/5"
          : "border-stroke-default bg-bg-elevated/40";
  return (
    <div className={`rounded-xl border p-4 ${ring}`}>
      <div className="text-ink-muted mb-1 flex items-center gap-1.5 text-[10px] tracking-wider uppercase">
        {icon}
        {label}
      </div>
      <div className="font-display text-ink-primary text-2xl font-semibold">{value}</div>
    </div>
  );
}
