import { requireSuperAdmin } from "@/lib/auth";
import { db } from "@/lib/db";
import { Badge, btn, Card, EmptyState, Field, PageHeader, StatCard, input } from "@/components/ui";
import { fmtDateTime, parseJSON } from "@/lib/utils";
import { isPushSendConfigured, getPushPublicConfig } from "@/lib/push";
import { PushToggle } from "@/components/push-toggle";
import { adminBroadcastPush } from "../actions";

export const metadata = { title: "Push notifications" };

export default async function AdminPushPage({
  searchParams,
}: {
  searchParams: Promise<{ result?: string; error?: string }>;
}) {
  await requireSuperAdmin();
  const { result, error } = await searchParams;
  const [total, registered, senderReady, clientReady, recentSends] = await Promise.all([
    db.pushToken.count(),
    db.pushToken.count({ where: { userId: { not: null } } }),
    isPushSendConfigured(),
    getPushPublicConfig(),
    db.auditLog.findMany({ where: { action: "admin.push.broadcast" }, orderBy: { createdAt: "desc" }, take: 8, include: { user: { select: { name: true } } } }),
  ]);
  const visitors = total - registered;
  const ready = senderReady && Boolean(clientReady);

  return (
    <main>
      <PageHeader
        title="📲 Push notifications"
        sub="Broadcast a browser notification to everyone subscribed — all devices, registered users only, or anonymous website visitors."
        action={<PushToggle />}
      />

      {!ready && (
        <p className="mb-4 rounded-xl bg-amber-500/10 px-4 py-2.5 text-sm font-medium text-amber-700">
          ⚠️ Configure Firebase first in <a href="/admin/settings" className="underline">System settings → Web push</a>.
        </p>
      )}
      {result && <p className="mb-4 rounded-xl bg-emerald-500/10 px-4 py-2.5 text-sm font-medium text-emerald-600">📲 {result}</p>}
      {error && <p className="mb-4 rounded-xl bg-red-500/10 px-4 py-2.5 text-sm font-medium text-red-600">{error}</p>}

      <div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard label="Subscribed Devices" value={total} />
        <StatCard label="Registered Users' Devices" value={registered} accent="text-indigo-600" />
        <StatCard label="Anonymous Visitors" value={visitors} accent="text-sky-600" />
        <StatCard label="Sender" value={ready ? "Ready" : "Off"} accent={ready ? "text-emerald-600" : "text-amber-600"} />
      </div>

      <div className="mt-6 grid gap-6 lg:grid-cols-[1fr_340px]">
        {/* Compose */}
        <Card className="p-6">
          <h2 className="text-sm font-bold text-zinc-100">Compose broadcast</h2>
          <p className="mb-4 text-xs text-zinc-500">Lands as a native browser notification on every subscribed device, even when the site is closed.</p>
          <form action={adminBroadcastPush} className="space-y-4">
            <Field name="title" title="Title *">
              <input id="title" name="title" required maxLength={80} placeholder="🎉 TechBharat Summit — early-bird passes live!" className={input} />
            </Field>
            <Field name="body" title="Message">
              <textarea id="body" name="body" rows={3} maxLength={200} placeholder="Short and punchy — this shows under the title on the notification." className={input} />
            </Field>
            <Field name="link" title="Open on click (link)">
              <input id="link" name="link" placeholder="/ or /c/techbharat-summit-2026 or a full https:// URL" className={input} />
            </Field>
            <div>
              <div className="mb-2 text-xs font-semibold text-zinc-400">Audience</div>
              <div className="grid gap-2 sm:grid-cols-3">
                {[
                  ["all", "🌐 Everyone", `${total} devices — users + visitors`],
                  ["registered", "👤 Registered users", `${registered} devices with accounts`],
                  ["visitors", "🪟 Anonymous visitors", `${visitors} devices without accounts`],
                ].map(([val, label, sub]) => (
                  <label key={val} className="flex cursor-pointer flex-col rounded-xl border border-white/80 bg-white/60 px-3.5 py-2.5 transition has-[:checked]:border-indigo-400 has-[:checked]:bg-indigo-500/10">
                    <span className="flex items-center gap-2 text-sm font-semibold text-zinc-200">
                      <input type="radio" name="audience" value={val} defaultChecked={val === "all"} className="accent-indigo-600" />
                      {label}
                    </span>
                    <span className="ml-5 mt-0.5 text-[11px] text-zinc-500">{sub}</span>
                  </label>
                ))}
              </div>
            </div>
            <button className={`${btn.primary} px-6 !py-3`} disabled={!ready}>📤 Send broadcast</button>
            <p className="text-[11px] text-zinc-600">Tip: switch to another tab/app before sending if you want to see your own notification pop — browsers often hide banners for the page you're looking at.</p>
          </form>
        </Card>

        {/* Recent sends */}
        <div>
          <h3 className="mb-2 text-sm font-bold text-zinc-200">Recent broadcasts</h3>
          {recentSends.length === 0 ? (
            <EmptyState title="Nothing sent yet" body="Your broadcast history appears here with delivery counts." />
          ) : (
            <div className="space-y-2">
              {recentSends.map((l) => {
                const meta = parseJSON<{ title?: string; audience?: string; devices?: number; sent?: number; failed?: number }>(l.meta, {});
                return (
                  <Card key={l.id} className="p-3.5">
                    <div className="flex items-start justify-between gap-2">
                      <span className="min-w-0 truncate text-sm font-semibold text-zinc-200">{meta.title ?? "Broadcast"}</span>
                      <Badge className="shrink-0 bg-indigo-500/10 text-indigo-600">{meta.audience ?? "all"}</Badge>
                    </div>
                    <div className="mt-1 text-[11px] text-zinc-500">
                      ✅ {meta.sent ?? 0} delivered{(meta.failed ?? 0) > 0 ? ` · ⚠️ ${meta.failed} failed` : ""} · {meta.devices ?? 0} devices
                    </div>
                    <div className="mt-0.5 text-[11px] text-zinc-600">{fmtDateTime(l.createdAt)}{l.user ? ` · ${l.user.name}` : ""}</div>
                  </Card>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </main>
  );
}
