import type { Metadata } from "next";
import { sql } from "drizzle-orm";
import {
  Database,
  Mail,
  ShieldCheck,
  Users,
  HeartPulse,
  AlertTriangle,
  CheckCircle2,
  XCircle,
} from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import {
  users,
  applications,
  emailLog,
  rateLimitEntries,
  redirects,
  courses,
  researchStudiesTable,
  storeProducts,
  blogPosts,
} from "@/lib/db/schema";
import { loadEnv } from "@/lib/env";
import { AdminHeading, FormSection, KpiCard, StatusBadge } from "@/components/admin";

export const metadata: Metadata = { title: "System health" };
export const dynamic = "force-dynamic";

async function timedQuery<T>(label: string, fn: () => Promise<T>) {
  const start = Date.now();
  try {
    const value = await fn();
    return { label, ok: true, value, ms: Date.now() - start };
  } catch (err) {
    return {
      label,
      ok: false,
      value: null,
      ms: Date.now() - start,
      error: err instanceof Error ? err.message : String(err),
    };
  }
}

export default async function AdminHealthPage() {
  await requireAdmin();

  const dbPing = await timedQuery("Database", async () => {
    const [row] = await db.execute(sql`select 1 as ok`);
    return row;
  });

  const [
    userCount,
    pendingApps,
    emailCounts,
    rateLimitRowCount,
    redirectCount,
    contentCounts,
  ] = await Promise.all([
    db
      .select({ n: sql<number>`count(*)`.mapWith(Number) })
      .from(users)
      .then((r) => r[0]?.n ?? 0),
    db
      .select({ n: sql<number>`count(*)`.mapWith(Number) })
      .from(applications)
      .where(sql`status = 'pending'`)
      .then((r) => r[0]?.n ?? 0),
    db
      .select({
        total: sql<number>`count(*)`.mapWith(Number),
        failed24h: sql<number>`count(*) filter (where status='failed' and created_at > now() - interval '24 hours')`.mapWith(Number),
        sent24h: sql<number>`count(*) filter (where status='sent' and created_at > now() - interval '24 hours')`.mapWith(Number),
        dev: sql<number>`count(*) filter (where status='dev_console')`.mapWith(Number),
      })
      .from(emailLog)
      .then((r) => r[0] ?? { total: 0, failed24h: 0, sent24h: 0, dev: 0 }),
    db
      .select({ n: sql<number>`count(*)`.mapWith(Number) })
      .from(rateLimitEntries)
      .then((r) => r[0]?.n ?? 0),
    db
      .select({ n: sql<number>`count(*)`.mapWith(Number) })
      .from(redirects)
      .where(sql`active = true`)
      .then((r) => r[0]?.n ?? 0),
    Promise.all([
      db
        .select({ n: sql<number>`count(*)`.mapWith(Number) })
        .from(courses)
        .then((r) => r[0]?.n ?? 0),
      db
        .select({ n: sql<number>`count(*)`.mapWith(Number) })
        .from(researchStudiesTable)
        .then((r) => r[0]?.n ?? 0),
      db
        .select({ n: sql<number>`count(*)`.mapWith(Number) })
        .from(storeProducts)
        .then((r) => r[0]?.n ?? 0),
      db
        .select({ n: sql<number>`count(*)`.mapWith(Number) })
        .from(blogPosts)
        .then((r) => r[0]?.n ?? 0),
    ]),
  ]);
  const [courseCount, studyCount, productCount, postCount] = contentCounts;

  const env = loadEnv();
  const emailConfigured = env.resendApiKey.length > 0;
  const checks: {
    label: string;
    ok: boolean;
    detail: string;
    Icon: typeof Database;
  }[] = [
    {
      label: "Database connection",
      ok: dbPing.ok,
      detail: dbPing.ok
        ? `Healthy · round-trip ${dbPing.ms}ms`
        : `Error: ${"error" in dbPing ? dbPing.error : "unknown"}`,
      Icon: Database,
    },
    {
      label: "Email delivery (Resend)",
      ok: emailConfigured,
      detail: emailConfigured
        ? "RESEND_API_KEY set — emails are being delivered."
        : "RESEND_API_KEY not set — emails log to the server console only.",
      Icon: Mail,
    },
    {
      label: "Auth secret",
      ok: env.nextAuthSecret.length >= 32,
      detail:
        env.nextAuthSecret.length >= 32
          ? `NEXTAUTH_SECRET is ${env.nextAuthSecret.length} chars.`
          : "NEXTAUTH_SECRET is shorter than 32 characters — regenerate for production.",
      Icon: ShieldCheck,
    },
    {
      label: "Approval-token secret",
      ok: env.approvalTokenSecret.length >= 32,
      detail:
        env.approvalTokenSecret.length >= 32
          ? "APPROVAL_TOKEN_SECRET configured."
          : "APPROVAL_TOKEN_SECRET is weak — regenerate.",
      Icon: ShieldCheck,
    },
    {
      label: "Admin notify addresses",
      ok: env.adminNotifyEmails.length > 0,
      detail: env.adminNotifyEmails.length
        ? env.adminNotifyEmails.join(", ")
        : "No ADMIN_NOTIFY_EMAILS configured — nobody will receive application emails.",
      Icon: Users,
    },
  ];

  const allOk = checks.every((c) => c.ok);

  return (
    <>
      <AdminHeading
        eyebrow="System"
        title="Health"
        lede="Live status of the database, email pipeline, secrets, and stored content."
        actions={
          allOk ? (
            <StatusBadge label="All systems healthy" tone="success" dot />
          ) : (
            <StatusBadge label="Attention required" tone="warning" dot />
          )
        }
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard label="Users" value={userCount} tone="ink" Icon={Users} />
        <KpiCard
          label="Pending applications"
          value={pendingApps}
          tone="blue"
        />
        <KpiCard
          label="Emails sent (24h)"
          value={emailCounts.sent24h}
          tone="emerald"
        />
        <KpiCard
          label="Emails failed (24h)"
          value={emailCounts.failed24h}
          tone={emailCounts.failed24h > 0 ? "red" : "slate"}
        />
      </div>

      <div className="grid gap-4 md:grid-cols-2">
        {checks.map((c) => (
          <FormSection key={c.label} title={c.label}>
            <div className="flex items-start gap-3">
              <div
                className={
                  c.ok
                    ? "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-emerald-50 text-emerald-600"
                    : "flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-red-50 text-red-600"
                }
              >
                {c.ok ? (
                  <CheckCircle2 className="h-5 w-5" aria-hidden />
                ) : (
                  <XCircle className="h-5 w-5" aria-hidden />
                )}
              </div>
              <div className="min-w-0 flex-1">
                <div className="font-semibold text-[14px] text-[var(--color-ink)]">
                  <c.Icon className="mr-1 inline h-4 w-4 align-[-2px]" aria-hidden />
                  {c.ok ? "Healthy" : "Needs attention"}
                </div>
                <p className="mt-1 text-[13px] leading-relaxed text-[var(--color-slate)]">
                  {c.detail}
                </p>
              </div>
            </div>
          </FormSection>
        ))}

        <FormSection title="Content">
          <dl className="grid grid-cols-2 gap-3 text-[13px]">
            <StatRow label="Courses" value={courseCount} />
            <StatRow label="Studies" value={studyCount} />
            <StatRow label="Store products" value={productCount} />
            <StatRow label="Blog posts" value={postCount} />
            <StatRow label="Redirects (active)" value={redirectCount} />
            <StatRow label="Email log rows" value={emailCounts.total} />
          </dl>
        </FormSection>

        <FormSection title="Throttling">
          <p className="text-[13px] text-[var(--color-slate)]">
            {rateLimitRowCount} active rate-limit buckets across login, join,
            and password-reset endpoints. Buckets expire automatically and are
            pruned nightly.
          </p>
          {emailCounts.dev > 0 && (
            <div className="mt-3 flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-[12px] text-amber-900">
              <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" aria-hidden />
              <span>
                <strong>{emailCounts.dev}</strong> dev-console emails on record.
                Configure RESEND_API_KEY to start delivering email.
              </span>
            </div>
          )}
        </FormSection>

        <FormSection title="Uptime" actions={<HeartPulse className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />}>
          <p className="text-[13px] text-[var(--color-slate)]">
            This page is rendered live on each request — if you can see it, the
            admin surface is reachable and the database is responding.
          </p>
        </FormSection>
      </div>
    </>
  );
}

function StatRow({ label, value }: { label: string; value: number }) {
  return (
    <>
      <dt className="text-[var(--color-slate)]">{label}</dt>
      <dd className="text-right font-mono font-semibold tabular-nums text-[var(--color-ink)]">
        {value.toLocaleString()}
      </dd>
    </>
  );
}
