import type { Metadata } from "next";
import Link from "next/link";
import { Inbox } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import {
  listApplicationsForAdmin,
  countPendingApplicationsAndProposals,
} from "@/lib/research/queries";
import {
  AdminHeading,
  DataTable,
  EmptyState,
  FilterPill,
  KpiCard,
  StatusBadge,
  Toolbar,
  formatAdminDateTime,
  type Column,
} from "@/components/admin";

export const metadata: Metadata = { title: "Research applications" };
export const dynamic = "force-dynamic";

const STATUS_FILTERS = ["all", "pending", "accepted", "declined", "withdrawn"] as const;
type StatusFilter = (typeof STATUS_FILTERS)[number];

function isStatusFilter(v: string | undefined): v is StatusFilter {
  return typeof v === "string" && (STATUS_FILTERS as readonly string[]).includes(v);
}

export default async function AdminResearchApplicationsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string }>;
}) {
  await requireAdmin();
  const params = await searchParams;
  const status: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const [rows, counts] = await Promise.all([
    listApplicationsForAdmin(status),
    countPendingApplicationsAndProposals(),
  ]);

  const columns: Column<(typeof rows)[number]>[] = [
    {
      key: "name",
      header: "Applicant",
      cell: (r) => (
        <div className="min-w-0">
          <Link
            href={`/admin/research/applications/${r.app.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {r.app.name}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">
            {r.app.email}
            {r.app.institution ? ` · ${r.app.institution}` : ""}
          </div>
        </div>
      ),
    },
    {
      key: "study",
      header: "Study",
      cell: (r) => (
        <div className="min-w-0">
          {r.studyTitle ? (
            <Link
              href={`/admin/research/${r.app.studyId ?? ""}`}
              className="truncate text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
            >
              {r.studyTitle}
            </Link>
          ) : (
            <span className="text-[13px] italic text-[var(--color-slate)]">
              General interest
            </span>
          )}
          {r.app.rolePreference && (
            <div className="text-[11px] text-[var(--color-slate)]">
              Role: {r.app.rolePreference}
            </div>
          )}
        </div>
      ),
    },
    {
      key: "status",
      header: "Status",
      cell: (r) => <StatusBadge label={r.app.status} dot />,
    },
    {
      key: "when",
      header: "Received",
      cell: (r) => (
        <span className="text-[12px] text-[var(--color-slate)]">
          {formatAdminDateTime(r.app.createdAt)}
        </span>
      ),
      className: "whitespace-nowrap",
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (r) => (
        <Link
          href={`/admin/research/applications/${r.app.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Review →
        </Link>
      ),
    },
  ];

  const pendingCount = rows.filter((r) => r.app.status === "pending").length;

  return (
    <>
      <AdminHeading
        eyebrow="Research"
        title="Study applications"
        lede="Members applying to collaborate on a specific study, or expressing general interest when no study is selected."
      />

      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-3">
        <KpiCard
          label="Pending applications"
          value={counts.applications}
          tone="blue"
          Icon={Inbox}
        />
        <KpiCard label="On this page" value={rows.length} tone="ink" />
        <KpiCard label="Pending right now" value={pendingCount} tone="emerald" />
      </div>

      <div className="mb-4">
        <Toolbar>
          {STATUS_FILTERS.map((s) => (
            <FilterPill
              key={s}
              href={`/admin/research/applications${s === "all" ? "" : `?status=${s}`}`}
              label={s}
              active={status === s}
            />
          ))}
        </Toolbar>
      </div>

      {rows.length === 0 ? (
        <EmptyState
          Icon={Inbox}
          title="No applications yet"
          description="Member applications to collaborate on studies show up here for review."
        />
      ) : (
        <DataTable columns={columns} rows={rows} rowKey={(r) => r.app.id} />
      )}
    </>
  );
}
