import type { Metadata } from "next";
import Link from "next/link";
import { desc, eq, sql } from "drizzle-orm";
import {
  Clock,
  CheckCircle2,
  XCircle,
  Users,
  FileText,
  GraduationCap,
  FlaskConical,
  ShoppingBag,
  Megaphone,
  UsersRound,
} from "lucide-react";
import { db } from "@/lib/db/client";
import {
  applications,
  users,
  adminAudit,
  blogPosts,
  courses,
  storeProducts,
  researchStudiesTable,
  teamMembers,
  notifications,
} from "@/lib/db/schema";
import {
  AdminHeading,
  KpiCard,
  DataTable,
  StatusBadge,
  EmptyState,
  FormSection,
  formatAdminDate,
  formatAdminRelative,
  type Column,
} from "@/components/admin";
import { Button } from "@/components/Button";

export const metadata: Metadata = {
  title: "Dashboard",
};

type RecentApp = {
  id: string;
  status: "pending" | "approved" | "rejected" | "withdrawn";
  createdAt: Date;
  name: string;
  email: string;
};

type RecentAudit = {
  id: string;
  action: string;
  createdAt: Date;
  adminName: string | null;
};

async function scalarCount(
  queryBuilder: Promise<Array<{ count: number }>>,
): Promise<number> {
  const [row] = await queryBuilder;
  return Number(row?.count ?? 0);
}

export default async function AdminDashboardPage() {
  const [
    appStatusRows,
    userStatusRows,
    blogPublished,
    coursesPublished,
    storeInStock,
    studiesActive,
    teamActive,
    notificationsActive,
    recentApplicationsRaw,
    recentAuditRaw,
  ] = await Promise.all([
    db
      .select({ status: applications.status, count: sql<number>`count(*)::int` })
      .from(applications)
      .groupBy(applications.status),
    db
      .select({ status: users.status, count: sql<number>`count(*)::int` })
      .from(users)
      .groupBy(users.status),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(blogPosts)
        .where(eq(blogPosts.status, "published")),
    ),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(courses)
        .where(eq(courses.status, "published")),
    ),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(storeProducts)
        .where(eq(storeProducts.status, "published")),
    ),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(researchStudiesTable)
        .where(eq(researchStudiesTable.status, "published")),
    ),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(teamMembers)
        .where(eq(teamMembers.status, "active")),
    ),
    scalarCount(
      db
        .select({ count: sql<number>`count(*)::int` })
        .from(notifications)
        .where(eq(notifications.active, true)),
    ),
    db
      .select({
        id: applications.id,
        status: applications.status,
        createdAt: applications.createdAt,
        name: users.name,
        email: users.email,
      })
      .from(applications)
      .innerJoin(users, eq(users.id, applications.userId))
      .orderBy(desc(applications.createdAt))
      .limit(6),
    db
      .select({
        id: adminAudit.id,
        action: adminAudit.action,
        createdAt: adminAudit.createdAt,
        adminName: users.name,
      })
      .from(adminAudit)
      .leftJoin(users, eq(users.id, adminAudit.adminUserId))
      .orderBy(desc(adminAudit.createdAt))
      .limit(8),
  ]);

  const recentApplications = recentApplicationsRaw as RecentApp[];
  const recentAudit = recentAuditRaw as RecentAudit[];

  const appByStatus = (key: string) =>
    Number(appStatusRows.find((r) => r.status === key)?.count ?? 0);
  const userByStatus = (key: string) =>
    Number(userStatusRows.find((r) => r.status === key)?.count ?? 0);

  const pendingCount = appByStatus("pending");
  const approvedCount = appByStatus("approved");
  const rejectedCount = appByStatus("rejected");
  const activeMembers = userByStatus("active");

  const appColumns: Column<RecentApp>[] = [
    {
      key: "applicant",
      header: "Applicant",
      cell: (r) => (
        <div className="min-w-0">
          <div className="truncate font-semibold text-[var(--color-ink)]">
            {r.name}
          </div>
          <div className="truncate text-[12px] text-[var(--color-slate)]">
            {r.email}
          </div>
        </div>
      ),
    },
    {
      key: "submitted",
      header: "Submitted",
      cell: (r) => (
        <span className="text-[13px] text-[var(--color-slate)]">
          {formatAdminRelative(r.createdAt)}
        </span>
      ),
    },
    {
      key: "status",
      header: "Status",
      cell: (r) => <StatusBadge label={r.status} dot />,
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (r) => (
        <Link
          href={`/admin/applications/${r.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Review →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Overview"
        title="Dashboard"
        lede="Membership, content, and operations at a glance."
        actions={
          <>
            <Button href="/admin/applications?status=pending" variant="primary" className="!px-4 !py-2 !text-[13px]">
              Pending applications
              {pendingCount > 0 && (
                <span className="ml-2 rounded-full bg-white/20 px-1.5 py-0.5 text-[11px]">
                  {pendingCount}
                </span>
              )}
            </Button>
            <Button href="/admin/blog" variant="ghost" className="!px-4 !py-2 !text-[13px]">
              New post
            </Button>
          </>
        }
      />

      <div className="grid grid-cols-2 gap-4 lg:grid-cols-4">
        <KpiCard
          label="Pending"
          value={pendingCount}
          Icon={Clock}
          tone="blue"
          href="/admin/applications?status=pending"
          hint="Applications awaiting review"
        />
        <KpiCard
          label="Approved"
          value={approvedCount}
          Icon={CheckCircle2}
          tone="emerald"
          hint="Lifetime approvals"
        />
        <KpiCard
          label="Rejected"
          value={rejectedCount}
          Icon={XCircle}
          tone="red"
          hint="Declined applicants"
        />
        <KpiCard
          label="Active members"
          value={activeMembers}
          Icon={Users}
          tone="ink"
          href="/admin/members"
        />
      </div>

      <section className="mt-8">
        <div className="mb-3 flex items-center justify-between">
          <h2 className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
            Content & commerce
          </h2>
        </div>
        <div className="grid grid-cols-2 gap-4 lg:grid-cols-5">
          <KpiCard
            label="Blog posts"
            value={blogPublished}
            Icon={FileText}
            tone="blue"
            href="/admin/blog"
            hint="Published"
          />
          <KpiCard
            label="Courses"
            value={coursesPublished}
            Icon={GraduationCap}
            tone="emerald"
            href="/admin/academy"
            hint="Published"
          />
          <KpiCard
            label="Studies"
            value={studiesActive}
            Icon={FlaskConical}
            tone="amber"
            href="/admin/research"
            hint="Published"
          />
          <KpiCard
            label="Store items"
            value={storeInStock}
            Icon={ShoppingBag}
            tone="ink"
            href="/admin/store"
            hint="Published"
          />
          <KpiCard
            label="Team active"
            value={teamActive}
            Icon={UsersRound}
            tone="slate"
            href="/admin/team"
          />
        </div>
      </section>

      <section className="mt-8 grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <FormSection
          title="Recent applications"
          actions={
            <Link
              href="/admin/applications"
              className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
            >
              View all →
            </Link>
          }
          padded={false}
        >
          {recentApplications.length === 0 ? (
            <EmptyState
              Icon={Users}
              title="No applications yet"
              description="Membership applications will appear here as they're submitted."
            />
          ) : (
            <DataTable
              columns={appColumns}
              rows={recentApplications}
              rowKey={(r) => r.id}
              dense
              className="!rounded-none !border-0"
            />
          )}
        </FormSection>

        <FormSection
          title="Admin activity"
          description={notificationsActive > 0 ? `${notificationsActive} notification banner${notificationsActive === 1 ? "" : "s"} live` : "No live banners"}
          actions={
            <Link
              href="/admin/audit"
              className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
            >
              Full log →
            </Link>
          }
        >
          {recentAudit.length === 0 ? (
            <EmptyState
              Icon={Megaphone}
              title="No activity yet"
              description="Admin actions will appear here as they happen."
            />
          ) : (
            <ul className="-mx-2 flex flex-col">
              {recentAudit.map((entry) => (
                <li
                  key={entry.id}
                  className="flex items-center justify-between gap-3 rounded-lg px-2 py-2.5 text-[13px] transition-colors hover:bg-[var(--color-mist)]/30"
                >
                  <div className="min-w-0">
                    <div className="truncate font-semibold text-[var(--color-ink)]">
                      {entry.action}
                    </div>
                    <div className="truncate text-[12px] text-[var(--color-slate)]">
                      {entry.adminName ?? "System"} · {formatAdminDate(entry.createdAt)}
                    </div>
                  </div>
                  <span className="shrink-0 text-[11px] uppercase tracking-wider text-[var(--color-slate)]">
                    {formatAdminRelative(entry.createdAt)}
                  </span>
                </li>
              ))}
            </ul>
          )}
        </FormSection>
      </section>
    </>
  );
}

export const dynamic = "force-dynamic";
