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

export const metadata: Metadata = { title: "Study proposals" };
export const dynamic = "force-dynamic";

const STATUS_FILTERS = ["all", "pending", "accepted", "declined"] 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 AdminResearchProposalsPage({
  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([
    listProposalsForAdmin(status),
    countPendingApplicationsAndProposals(),
  ]);

  const columns: Column<(typeof rows)[number]>[] = [
    {
      key: "title",
      header: "Proposal",
      cell: (p) => (
        <div className="min-w-0">
          <Link
            href={`/admin/research/proposals/${p.id}`}
            className="truncate font-semibold text-[var(--color-ink)] hover:text-[var(--color-blue)]"
          >
            {p.title}
          </Link>
          <div className="truncate text-[12px] text-[var(--color-slate)]">
            {p.proposerName} · {p.institution || "—"}
          </div>
        </div>
      ),
    },
    {
      key: "specialty",
      header: "Specialty",
      cell: (p) => p.specialty || "—",
      className: "whitespace-nowrap text-[13px] text-[var(--color-slate)]",
    },
    {
      key: "status",
      header: "Status",
      cell: (p) => <StatusBadge label={p.status} dot />,
    },
    {
      key: "when",
      header: "Received",
      cell: (p) => (
        <span className="text-[12px] text-[var(--color-slate)]">
          {formatAdminDateTime(p.createdAt)}
        </span>
      ),
      className: "whitespace-nowrap",
    },
    {
      key: "actions",
      header: "",
      align: "right",
      cell: (p) => (
        <Link
          href={`/admin/research/proposals/${p.id}`}
          className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
        >
          Review →
        </Link>
      ),
    },
  ];

  return (
    <>
      <AdminHeading
        eyebrow="Research"
        title="Study proposals"
        lede="Ideas submitted by the community via /products/research/proposals/new. Review and respond with an accept or decline."
      />
      <div className="mb-6 grid grid-cols-2 gap-4 lg:grid-cols-3">
        <KpiCard
          label="Pending proposals"
          value={counts.proposals}
          tone="blue"
          Icon={Lightbulb}
        />
        <KpiCard label="On this page" value={rows.length} tone="ink" />
        <KpiCard
          label="Pending right now"
          value={rows.filter((r) => r.status === "pending").length}
          tone="emerald"
        />
      </div>

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

      {rows.length === 0 ? (
        <EmptyState
          Icon={Lightbulb}
          title="No proposals yet"
          description="Proposals submitted through the public form show up here for committee review."
        />
      ) : (
        <DataTable columns={columns} rows={rows} rowKey={(p) => p.id} />
      )}
    </>
  );
}
