import type { Metadata } from "next";
import Link from "next/link";
import { desc, eq } from "drizzle-orm";
import { UserCheck } from "lucide-react";
import { db } from "@/lib/db/client";
import { applications, users } from "@/lib/db/schema";
import {
  AdminHeading,
  DataTable,
  StatusBadge,
  EmptyState,
  Toolbar,
  FilterPill,
  SearchInput,
  formatAdminRelative,
  type Column,
} from "@/components/admin";

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

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

const STATUS_FILTERS = ["all", "pending", "approved", "rejected", "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 AdminApplicationsPage({
  searchParams,
}: {
  searchParams: Promise<{ status?: string; q?: string }>;
}) {
  const params = await searchParams;
  const statusFilter: StatusFilter = isStatusFilter(params.status) ? params.status : "all";
  const query = (params.q ?? "").trim().toLowerCase();

  const rows = (await db
    .select({
      id: applications.id,
      status: applications.status,
      createdAt: applications.createdAt,
      name: users.name,
      email: users.email,
      institution: users.institution,
      country: users.country,
    })
    .from(applications)
    .innerJoin(users, eq(users.id, applications.userId))
    .orderBy(desc(applications.createdAt))) as Row[];

  const counts = rows.reduce<Record<string, number>>((acc, r) => {
    acc[r.status] = (acc[r.status] ?? 0) + 1;
    return acc;
  }, {});

  let filtered = rows;
  if (statusFilter !== "all") {
    filtered = filtered.filter((r) => r.status === statusFilter);
  }
  if (query) {
    filtered = filtered.filter((r) =>
      [r.name, r.email, r.institution, r.country]
        .join(" ")
        .toLowerCase()
        .includes(query),
    );
  }

  const columns: Column<Row>[] = [
    {
      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: "institution",
      header: "Institution",
      cell: (r) => (
        <span className="text-[13px] text-[var(--color-ink)]/80">{r.institution}</span>
      ),
    },
    {
      key: "country",
      header: "Country",
      cell: (r) => (
        <span className="text-[13px] text-[var(--color-slate)]">{r.country}</span>
      ),
    },
    {
      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>
      ),
    },
  ];

  const buildHref = (status: StatusFilter) => {
    const parts: string[] = [];
    if (status !== "all") parts.push(`status=${status}`);
    if (query) parts.push(`q=${encodeURIComponent(query)}`);
    return `/admin/applications${parts.length ? `?${parts.join("&")}` : ""}`;
  };

  return (
    <>
      <AdminHeading
        eyebrow="People"
        title="Applications"
        lede="Review membership submissions from surgeons, researchers, and trainees."
      />

      <div className="mb-4">
        <Toolbar
          actions={
            <form method="GET" action="/admin/applications">
              {statusFilter !== "all" && (
                <input type="hidden" name="status" value={statusFilter} />
              )}
              <SearchInput
                name="q"
                defaultValue={params.q ?? ""}
                placeholder="Search by name, email, institution…"
              />
            </form>
          }
        >
          <FilterPill
            href={buildHref("all")}
            label="All"
            count={rows.length}
            active={statusFilter === "all"}
          />
          <FilterPill
            href={buildHref("pending")}
            label="Pending"
            count={counts.pending ?? 0}
            active={statusFilter === "pending"}
          />
          <FilterPill
            href={buildHref("approved")}
            label="Approved"
            count={counts.approved ?? 0}
            active={statusFilter === "approved"}
          />
          <FilterPill
            href={buildHref("rejected")}
            label="Rejected"
            count={counts.rejected ?? 0}
            active={statusFilter === "rejected"}
          />
          <FilterPill
            href={buildHref("withdrawn")}
            label="Withdrawn"
            count={counts.withdrawn ?? 0}
            active={statusFilter === "withdrawn"}
          />
        </Toolbar>
      </div>

      {filtered.length === 0 ? (
        <EmptyState
          Icon={UserCheck}
          title={query || statusFilter !== "all" ? "No matching applications" : "No applications yet"}
          description={
            query || statusFilter !== "all"
              ? "Try clearing the filter or search term."
              : "Membership applications will appear here as they're submitted."
          }
          action={
            (query || statusFilter !== "all") && (
              <Link
                href="/admin/applications"
                className="text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
              >
                Clear filters
              </Link>
            )
          }
        />
      ) : (
        <DataTable
          columns={columns}
          rows={filtered}
          rowKey={(r) => r.id}
        />
      )}
    </>
  );
}
