import type { Metadata } from "next";
import Link from "next/link";
import Image from "next/image";
import { and, eq, ilike, or, sql, desc } from "drizzle-orm";
import { Search, Users, ExternalLink } from "lucide-react";
import { requireUser } from "@/lib/auth/admin-guard";
import { db } from "@/lib/db/client";
import { users } from "@/lib/db/schema";

export const metadata: Metadata = {
  title: "Member directory",
  robots: { index: false, follow: false },
};
export const dynamic = "force-dynamic";

function initials(name: string): string {
  return name
    .trim()
    .split(/\s+/)
    .map((p) => p[0]?.toUpperCase() ?? "")
    .slice(0, 2)
    .join("");
}

export default async function DirectoryPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; country?: string }>;
}) {
  await requireUser();
  const params = await searchParams;
  const q = (params.q ?? "").trim();
  const countryFilter = (params.country ?? "").trim();

  const whereParts: ReturnType<typeof eq>[] = [
    eq(users.status, "active"),
    eq(users.visibleInDirectory, true),
  ];
  if (q) {
    whereParts.push(
      or(
        ilike(users.name, `%${q}%`),
        ilike(users.institution, `%${q}%`),
        ilike(users.specialty, `%${q}%`),
        ilike(users.bio, `%${q}%`),
      )!,
    );
  }
  if (countryFilter) {
    whereParts.push(eq(users.country, countryFilter));
  }

  const rows = await db
    .select({
      id: users.id,
      name: users.name,
      institution: users.institution,
      country: users.country,
      professionalRole: users.professionalRole,
      specialty: users.specialty,
      bio: users.bio,
      avatarPath: users.avatarPath,
      orcidUrl: users.orcidUrl,
      linkedinUrl: users.linkedinUrl,
      websiteUrl: users.websiteUrl,
      role: users.role,
    })
    .from(users)
    .where(and(...whereParts))
    .orderBy(desc(users.role), users.name)
    .limit(200);

  const [{ total }] = await db
    .select({ total: sql<number>`count(*)`.mapWith(Number) })
    .from(users)
    .where(and(eq(users.status, "active"), eq(users.visibleInDirectory, true)));

  // Top-N countries for the facet pill bar.
  const countryRows = await db
    .select({
      country: users.country,
      n: sql<number>`count(*)`.mapWith(Number),
    })
    .from(users)
    .where(and(eq(users.status, "active"), eq(users.visibleInDirectory, true)))
    .groupBy(users.country)
    .orderBy(desc(sql<number>`count(*)`))
    .limit(8);

  return (
    <>
      <div className="mb-6 flex items-start gap-4">
        <span className="flex h-11 w-11 shrink-0 items-center justify-center rounded-xl bg-[var(--color-mist)] text-[var(--color-blue)]">
          <Users className="h-5 w-5" aria-hidden />
        </span>
        <div className="min-w-0 flex-1">
          <div className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-blue)]">
            Community
          </div>
          <h1 className="mt-1 font-display text-[28px] md:text-[34px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
            Member directory
          </h1>
          <p className="mt-2 max-w-2xl text-[14px] leading-relaxed text-[var(--color-slate)]">
            Every active member who&rsquo;s chosen to appear in the directory.
            Email is never shown — reach out via the public links each member
            has published.
          </p>
        </div>
      </div>

      <form method="GET" className="mb-5">
        <div className="flex flex-wrap items-center gap-2">
          <div className="relative w-full flex-1 sm:min-w-[260px] sm:w-auto">
            <Search
              className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-[var(--color-slate)]"
              aria-hidden
            />
            <input
              type="search"
              name="q"
              defaultValue={q}
              placeholder="Search name, institution, specialty…"
              className="w-full rounded-lg border border-[var(--color-line)] bg-white py-2 pl-9 pr-3 text-[14px] focus:border-[var(--color-blue)] focus:outline-none focus:ring-2 focus:ring-[var(--color-mist)]"
            />
          </div>
          {countryFilter && (
            <input type="hidden" name="country" value={countryFilter} />
          )}
          <button
            type="submit"
            className="rounded-lg bg-[var(--color-blue)] px-4 py-2 text-[13px] font-semibold text-white hover:opacity-90"
          >
            Search
          </button>
          {(q || countryFilter) && (
            <Link
              href="/account/directory"
              className="rounded-lg border border-[var(--color-line)] bg-white px-4 py-2 text-[13px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
            >
              Clear
            </Link>
          )}
        </div>
        {countryRows.length > 0 && (
          <div className="mt-3 flex flex-wrap items-center gap-2">
            <span className="text-[11px] font-bold uppercase tracking-[0.15em] text-[var(--color-slate)]">
              Country
            </span>
            <Link
              href={`/account/directory${q ? `?q=${encodeURIComponent(q)}` : ""}`}
              className={
                !countryFilter
                  ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                  : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
              }
            >
              All
            </Link>
            {countryRows.map((c) => {
              const active = countryFilter === c.country;
              const href = `/account/directory?${new URLSearchParams({
                ...(q ? { q } : {}),
                country: c.country,
              }).toString()}`;
              return (
                <Link
                  key={c.country}
                  href={href}
                  className={
                    active
                      ? "rounded-full bg-[var(--color-blue)] px-3 py-1 text-[12px] font-semibold text-white"
                      : "rounded-full bg-[var(--color-line)]/50 px-3 py-1 text-[12px] font-semibold text-[var(--color-ink)] hover:bg-[var(--color-mist)] hover:text-[var(--color-blue)]"
                  }
                >
                  {c.country} · {c.n}
                </Link>
              );
            })}
          </div>
        )}
      </form>

      <div className="mb-4 text-[12px] font-semibold text-[var(--color-slate)]">
        Showing {rows.length} of {total.toLocaleString()} members
      </div>

      {rows.length === 0 ? (
        <div className="rounded-2xl border border-[var(--color-line)] bg-[var(--color-mist)]/40 p-10 text-center">
          <Users
            className="mx-auto h-8 w-8 text-[var(--color-slate)]"
            aria-hidden
          />
          <h2 className="mt-4 font-display text-[20px] font-extrabold text-[var(--color-ink)]">
            No members match
          </h2>
          <p className="mt-2 text-[14px] text-[var(--color-slate)]">
            Try a broader search, or clear filters.
          </p>
        </div>
      ) : (
        <ul className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {rows.map((m) => (
            <li
              key={m.id}
              className="flex flex-col rounded-2xl border border-[var(--color-line)] bg-white p-5 transition-[border-color] hover:border-[var(--color-blue)]"
            >
              <div className="flex items-start gap-3">
                <div className="relative flex h-12 w-12 shrink-0 items-center justify-center overflow-hidden rounded-full bg-[var(--color-mist)] text-[var(--color-blue)]">
                  {m.avatarPath ? (
                    <Image
                      src={m.avatarPath}
                      alt=""
                      width={48}
                      height={48}
                      className="h-full w-full object-cover"
                    />
                  ) : (
                    <span className="font-display text-[14px] font-extrabold">
                      {initials(m.name) || "?"}
                    </span>
                  )}
                </div>
                <div className="min-w-0 flex-1">
                  <div className="font-display text-[16px] font-extrabold text-[var(--color-ink)]">
                    {m.name}
                    {m.role === "admin" && (
                      <span className="ml-1.5 inline-flex items-center gap-1 rounded-full bg-[var(--color-blue)] px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-white align-middle">
                        Admin
                      </span>
                    )}
                  </div>
                  <div className="mt-0.5 text-[12px] text-[var(--color-slate)]">
                    {m.institution}
                  </div>
                  <div className="mt-0.5 text-[11px] font-semibold uppercase tracking-wider text-[var(--color-slate)]">
                    {m.country}
                    {m.professionalRole ? ` · ${m.professionalRole}` : ""}
                  </div>
                </div>
              </div>
              {m.specialty && (
                <span className="mt-3 inline-flex self-start rounded-full bg-[var(--color-mist)] px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  {m.specialty}
                </span>
              )}
              {m.bio && (
                <p className="mt-3 line-clamp-3 text-[13px] leading-relaxed text-[var(--color-ink)]/80">
                  {m.bio}
                </p>
              )}
              {(m.orcidUrl || m.linkedinUrl || m.websiteUrl) && (
                <div className="mt-4 flex flex-wrap gap-1.5 border-t border-[var(--color-line)] pt-3">
                  {m.orcidUrl && (
                    <LinkBadge href={m.orcidUrl} label="ORCID" />
                  )}
                  {m.linkedinUrl && (
                    <LinkBadge href={m.linkedinUrl} label="LinkedIn" />
                  )}
                  {m.websiteUrl && (
                    <LinkBadge href={m.websiteUrl} label="Website" />
                  )}
                </div>
              )}
            </li>
          ))}
        </ul>
      )}
    </>
  );
}

function LinkBadge({ href, label }: { href: string; label: string }) {
  return (
    <a
      href={href}
      target="_blank"
      rel="noreferrer noopener"
      className="inline-flex items-center gap-1 rounded-md border border-[var(--color-line)] bg-white px-2 py-0.5 text-[11px] font-semibold text-[var(--color-ink)] hover:border-[var(--color-blue)] hover:text-[var(--color-blue)]"
    >
      {label} <ExternalLink className="h-3 w-3" aria-hidden />
    </a>
  );
}
