import { prisma } from "@/lib/db";
import { NewsletterTable, type SubRow } from "./_table";

export const dynamic = "force-dynamic";

export default async function NewsletterAdminPage() {
  const [all, subscribed, unsubscribed, recent7d, sources] = await Promise.all([
    prisma.newsletterSubscriber.count(),
    prisma.newsletterSubscriber.count({ where: { status: "subscribed" } }),
    prisma.newsletterSubscriber.count({ where: { status: "unsubscribed" } }),
    prisma.newsletterSubscriber.count({
      where: {
        createdAt: { gte: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000) },
        status: "subscribed",
      },
    }),
    prisma.newsletterSubscriber.groupBy({
      by: ["source"],
      _count: true,
      orderBy: { source: "asc" },
    }),
  ]);

  const rows: SubRow[] = (
    await prisma.newsletterSubscriber.findMany({
      orderBy: { createdAt: "desc" },
      take: 500,
      select: {
        id: true,
        email: true,
        status: true,
        source: true,
        confirmedAt: true,
        unsubscribedAt: true,
        createdAt: true,
      },
    })
  ).map((r) => ({
    id: r.id,
    email: r.email,
    status: r.status,
    source: r.source,
    confirmedAt: r.confirmedAt,
    unsubscribedAt: r.unsubscribedAt,
    createdAt: r.createdAt,
  }));

  return (
    <div>
      <div className="mb-6">
        <h1 className="font-display text-2xl lg:text-3xl font-bold mb-1">Newsletter</h1>
        <p className="text-sm text-ink-muted">
          Danh sách email đã đăng ký nhận tin. Hiển thị tối đa 500 entries mới nhất, xuất CSV để
          làm việc với toàn bộ dữ liệu.
        </p>
      </div>

      <div className="grid gap-3 grid-cols-2 lg:grid-cols-4 mb-6">
        <Stat label="Tổng" value={all} />
        <Stat label="Đang subscribe" value={subscribed} hint={`${unsubscribed} đã huỷ`} />
        <Stat label="7 ngày qua" value={recent7d} hint="subscribers mới" />
        <Stat
          label="Nguồn"
          value={sources.length}
          hint={sources.map((s) => `${s.source}:${s._count}`).join(" · ")}
        />
      </div>

      <NewsletterTable rows={rows} />
    </div>
  );
}

function Stat({ label, value, hint }: { label: string; value: number; hint?: string }) {
  return (
    <div className="rounded-xl border border-stroke-subtle bg-bg-elevated/40 p-5">
      <div className="text-[11px] uppercase tracking-[0.18em] text-ink-muted">{label}</div>
      <div className="font-display text-3xl font-semibold mt-2">{value.toLocaleString("vi-VN")}</div>
      {hint ? <div className="text-xs text-ink-muted mt-1 truncate">{hint}</div> : null}
    </div>
  );
}
