import { redirect } from "next/navigation";
import { and, eq } from "drizzle-orm";
import { db } from "@db/client";
import { events, users, orders } from "@db/schema";
import { getCurrentRole } from "@/lib/auth";
import { formatPrice } from "@/lib/format";
import {
  Users as UsersIcon,
  CalendarDays,
  CheckCircle2,
  Banknote,
  Wallet,
  Undo2,
  BarChart3,
  ScrollText,
  Tags,
  Images,
  ImagePlus,
  Settings,
  type LucideIcon,
} from "lucide-react";
import { PageHeader, StatCard, ToolCard } from "@/components/ui";

export const metadata = { title: "Overview · Admin" };

// Platform-wide overview. All counts read across every organizer -- there's
// no RLS admin-override doing this implicitly anymore; the caller must
// already be confirmed admin, which is what admin/layout.tsx's gate is for.
export default async function AdminOverviewPage() {
  const { isAdmin } = await getCurrentRole();
  if (!isAdmin) redirect("/dashboard");

  const [allEvents, organizerCount, paidOrders] = await Promise.all([
    db.select({ id: events.id, status: events.status }).from(events),
    db.$count(users, eq(users.role, "organizer")),
    db
      .select({ totalCents: orders.totalCents })
      .from(orders)
      .where(and(eq(orders.status, "paid"), eq(orders.currency, "kes"))),
  ]);

  const eventCount = allEvents.length;
  const publishedCount = allEvents.filter((e) => e.status === "published").length;
  // VibePass is KES-only (see AGENTS.md) -- a handful of pre-migration
  // Stripe/USD orders still exist, excluded here so they can't get silently
  // summed into a KES total (see the note in db/queries/payouts.ts).
  const grossCents = paidOrders.reduce((sum, o) => sum + o.totalCents, 0);
  const currency = "kes";

  const tools: { href: string; icon: LucideIcon; title: string; body: string }[] = [
    { href: "/admin/events", icon: CalendarDays, title: "Events", body: "All events — feature or take down." },
    { href: "/admin/organizers", icon: UsersIcon, title: "Organizers", body: "Suspend, ban, verify payout details." },
    { href: "/admin/earnings", icon: Wallet, title: "Earnings", body: "What each organizer is owed, platform-wide." },
    { href: "/admin/payouts", icon: Banknote, title: "Payouts", body: "Run M-Pesa & record bank disbursements." },
    { href: "/admin/refunds", icon: Undo2, title: "Refunds", body: "Issue organizer-requested refunds." },
    { href: "/admin/reports", icon: BarChart3, title: "Reports", body: "GMV, fees, tickets & top performers." },
    { href: "/admin/audit", icon: ScrollText, title: "Audit log", body: "Recent administrative actions." },
    { href: "/admin/categories", icon: Tags, title: "Categories", body: "Event taxonomy fans filter by." },
    { href: "/admin/gallery", icon: Images, title: "Gallery", body: "Albums and photos on the public site." },
    { href: "/admin/gallery/submissions", icon: ImagePlus, title: "Submissions", body: "Approve photographer uploads." },
    { href: "/admin/settings", icon: Settings, title: "Site settings", body: "Stats, platform fees, marketing images." },
  ];

  return (
    <div className="space-y-8">
      <PageHeader
        icon={BarChart3}
        title="Platform overview"
        description="Across every organizer on VibePass."
      />

      <section className="grid grid-cols-2 gap-3 sm:grid-cols-4">
        <StatCard icon={UsersIcon} label="Organizers" value={organizerCount.toString()} />
        <StatCard icon={CalendarDays} label="Events" value={eventCount.toString()} />
        <StatCard
          icon={CheckCircle2}
          label="Published"
          value={publishedCount.toString()}
          accent="gold"
        />
        <StatCard
          icon={Wallet}
          label="Gross sales"
          value={formatPrice(grossCents, currency)}
          hint="Paid orders, all time"
        />
      </section>

      <section className="space-y-3">
        <h2 className="text-sm font-semibold uppercase tracking-wider text-be-muted">Tools</h2>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {tools.map((t) => (
            <ToolCard key={t.href} href={t.href} icon={t.icon} title={t.title} body={t.body} />
          ))}
        </div>
      </section>
    </div>
  );
}
