import { Shell } from "@/components/Shell";
import { PageHeader } from "@/components/PageHeader";
import { PersonCard } from "@/components/PersonCard";
import { db, people as peopleTable } from "@/db";
import { and, asc, eq, inArray } from "drizzle-orm";
import { matchPeople } from "@/lib/match";
import { officeLabel } from "@/lib/format";
import type { Office } from "@/db/schema";
import Link from "next/link";

export const metadata = { title: "People" };

export default async function PeoplePage({ searchParams }: { searchParams: Promise<{ q?: string; office?: string; dept?: string }> }) {
  const { q = "", office, dept } = await searchParams;
  const offices = office ? [office as Office] : undefined;
  const departments = dept ? [dept] : undefined;
  const allDepts = (await db.selectDistinct({ department: peopleTable.department }).from(peopleTable).where(eq(peopleTable.isActive, true)).orderBy(asc(peopleTable.department))).map((d) => d.department);

  let people: { slug: string; firstName: string; lastName: string; title: string; department: string; office: Office; photoUrl: string | null; skills: string[]; reasons?: string[] }[];
  if (q.trim()) {
    const results = await matchPeople({ query: q, offices, departments, limit: 60 });
    people = results.map((r) => ({ ...r.person, skills: r.matchedSkills, reasons: r.reasons }));
  } else {
    const rows = await db.query.people.findMany({
      where: and(eq(peopleTable.isActive, true), offices ? inArray(peopleTable.office, offices) : undefined, departments ? inArray(peopleTable.department, departments) : undefined),
      orderBy: asc(peopleTable.lastName),
      with: { skills: { with: { skill: true }, orderBy: (ps, { desc }) => desc(ps.level) } },
    });
    people = rows.map((p) => ({ ...p, skills: p.skills.map((s) => s.skill.name) }));
  }

  const link = (params: Record<string, string | undefined>) => {
    const sp = new URLSearchParams();
    for (const [k, v] of Object.entries({ q, office, dept, ...params })) if (v) sp.set(k, v);
    return `/people?${sp.toString()}`;
  };

  return (
    <Shell>
      <PageHeader eyebrow="People" title={<>Makers, thinkers <span className="serif-i">&amp; doers.</span></>} intro="Search by name, skill, tool, client, vertical or interest. Try “react accessibility”, “sailing”, or “health research Boston”.">
        <form className="flex flex-wrap gap-2 max-w-3xl">
          <input name="q" defaultValue={q} placeholder="Search people…" className="flex-1 min-w-60 rounded-full border border-line bg-white px-5 py-2.5 text-sm focus:outline-none focus:border-ink" />
          {office && <input type="hidden" name="office" value={office} />}
          {dept && <input type="hidden" name="dept" value={dept} />}
          <button className="btn btn-ink">Search</button>
        </form>
        <div className="mt-4 flex flex-wrap gap-1.5 text-xs">
          <Link href={link({ office: undefined })} className={`chip ${!office ? "bg-ink text-white" : ""}`}>All offices</Link>
          {(Object.keys(officeLabel) as Office[]).map((o) => (
            <Link key={o} href={link({ office: o })} className={`chip ${office === o ? "bg-ink text-white" : ""}`}>{officeLabel[o]}</Link>
          ))}
          <span className="w-px bg-line mx-1" />
          <Link href={link({ dept: undefined })} className={`chip ${!dept ? "bg-ink text-white" : ""}`}>All teams</Link>
          {allDepts.map((d) => (
            <Link key={d} href={link({ dept: d })} className={`chip ${dept === d ? "bg-ink text-white" : ""}`}>{d}</Link>
          ))}
        </div>
      </PageHeader>
      <section className="mx-auto max-w-7xl px-5 pb-16">
        <p className="text-sm text-mist mb-4">{people.length} {people.length === 1 ? "person" : "people"}{q && ` matching “${q}”`}</p>
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {people.map((p) => (
            <PersonCard key={p.slug} person={p} skills={p.skills} footer={p.reasons?.length ? <p className="mt-3 text-xs text-soul-deep">{p.reasons[0]}</p> : null} />
          ))}
        </div>
        {people.length === 0 && <p className="text-ink/60">Nobody matched. Try fewer words, or a broader skill like “video” or “analytics”.</p>}
      </section>
    </Shell>
  );
}
