import type { Metadata } from "next";
import Link from "next/link";
import { ExternalLink } from "lucide-react";
import { db, users, auditLogs, count, eq, sql, like, desc } from "@epicure/db";
import { getAllSiteSettings, getSiteSetting } from "@/lib/site-settings";
import { isStripeTestMode } from "@/lib/stripe";
import { AdminSettingsForm } from "@/components/admin/admin-settings-form";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { requireFullAdminPage } from "@/lib/require-admin-page";

export const metadata: Metadata = {};

const STRIPE_GROUP = {
  title: "Stripe Connection",
  description:
    "Get keys from your Stripe Dashboard (Developers -> API keys). The webhook secret comes from " +
    "the endpoint you configure there pointed at /api/webhooks/stripe (events: checkout.session.completed, " +
    "customer.subscription.updated, customer.subscription.deleted, invoice.payment_failed, invoice.paid). " +
    "Price/Product IDs per tier are set on the Tier Limits page, not here.",
  keys: ["STRIPE_SECRET_KEY", "STRIPE_PUBLISHABLE_KEY", "STRIPE_WEBHOOK_SECRET"] as const,
};

export default async function AdminBillingPage() {
  await requireFullAdminPage();

  const [settings, secretKey] = await Promise.all([
    getAllSiteSettings(),
    getSiteSetting("STRIPE_SECRET_KEY"),
  ]);

  const [subscriberCounts, pastDueUsers, recentBillingEvents] = await Promise.all([
    db.select({ tier: users.tier, count: count() }).from(users).where(sql`${users.tier} != 'free'`).groupBy(users.tier),
    db
      .select({ id: users.id, name: users.name, email: users.email })
      .from(users)
      .where(eq(users.subscriptionStatus, "past_due"))
      .limit(20),
    db
      .select({ id: auditLogs.id, action: auditLogs.action, targetId: auditLogs.targetId, metadata: auditLogs.metadata, createdAt: auditLogs.createdAt })
      .from(auditLogs)
      .where(like(auditLogs.action, "billing.%"))
      .orderBy(desc(auditLogs.createdAt))
      .limit(20),
  ]);

  const proCount = subscriberCounts.find((r) => r.tier === "pro")?.count ?? 0;
  const familyCount = subscriberCounts.find((r) => r.tier === "family")?.count ?? 0;

  return (
    <div className="space-y-8">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">Billing</h1>
        <p className="text-muted-foreground text-sm mt-1">
          Stripe connection status, subscriber insights, and recent billing events. Price mapping per tier
          lives on the <Link href="/admin/tiers" className="underline underline-offset-4">Tier Limits</Link> page.
        </p>
      </div>

      <div className="flex items-center gap-2">
        {secretKey ? (
          <Badge variant={isStripeTestMode(secretKey) ? "secondary" : "default"}>
            {isStripeTestMode(secretKey) ? "Test mode" : "Live mode"}
          </Badge>
        ) : (
          <Badge variant="outline" className="text-muted-foreground">Not configured</Badge>
        )}
        <a
          href="https://dashboard.stripe.com"
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1 text-sm text-primary hover:underline"
        >
          Stripe Dashboard
          <ExternalLink className="h-3.5 w-3.5" />
        </a>
      </div>

      <AdminSettingsForm group={STRIPE_GROUP} settings={settings} />

      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <Card>
          <CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Pro subscribers</CardTitle></CardHeader>
          <CardContent><p className="text-2xl font-bold">{proCount}</p></CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Family subscribers</CardTitle></CardHeader>
          <CardContent><p className="text-2xl font-bold">{familyCount}</p></CardContent>
        </Card>
        <Card>
          <CardHeader><CardTitle className="text-sm font-medium text-muted-foreground">Past due</CardTitle></CardHeader>
          <CardContent><p className="text-2xl font-bold">{pastDueUsers.length}</p></CardContent>
        </Card>
      </div>

      {pastDueUsers.length > 0 && (
        <section className="rounded-xl border p-6 space-y-3">
          <h2 className="font-semibold text-lg">Payments needing attention</h2>
          <ul className="space-y-1.5">
            {pastDueUsers.map((u) => (
              <li key={u.id} className="flex items-center justify-between text-sm">
                <span>{u.name} <span className="text-muted-foreground">({u.email})</span></span>
                <Link href={`/admin/users/${u.id}`} className="text-primary hover:underline">View</Link>
              </li>
            ))}
          </ul>
        </section>
      )}

      <section className="rounded-xl border p-6 space-y-3">
        <h2 className="font-semibold text-lg">Recent billing events</h2>
        {recentBillingEvents.length === 0 ? (
          <p className="text-sm text-muted-foreground">Nothing yet.</p>
        ) : (
          <ul className="space-y-1.5">
            {recentBillingEvents.map((e) => (
              <li key={e.id} className="flex items-center justify-between text-sm border-b last:border-0 pb-1.5">
                <span>
                  <span className="font-mono text-xs">{e.action}</span>
                  {e.targetId && (
                    <Link href={`/admin/users/${e.targetId}`} className="text-primary hover:underline ml-2">user</Link>
                  )}
                </span>
                <span className="text-muted-foreground text-xs">{e.createdAt.toLocaleString()}</span>
              </li>
            ))}
          </ul>
        )}
      </section>
    </div>
  );
}
