import { Shell } from "@/components/Shell";
import { PageHeader } from "@/components/PageHeader";
import { FindForm } from "./FindForm";
import { matchPeople, suggestTeam } from "@/lib/match";
import { Avatar } from "@/components/Avatar";
import { officeLabel, fullName } from "@/lib/format";
import type { Office } from "@/db/schema";
import Link from "next/link";

export const metadata = { title: "Find a team" };

const examples = [
  "Hospitality client wants a direct-booking app with a CRO programme. Boston-based, Spanish speaking a plus.",
  "Public transport rebrand and launch film for an Irish state body – integrated campaign, OOH and social.",
  "Health-tech patient portal: discovery research, accessible UX and a React Native build.",
  "University enrolment campaign – paid social, landing pages, GA4 reporting.",
];

export default async function FindPage({ searchParams }: { searchParams: Promise<{ q?: string; office?: string; available?: string; size?: string }> }) {
  const { q = "", office, available, size } = await searchParams;
  const teamSize = Math.min(8, Math.max(3, parseInt(size ?? "5", 10) || 5));
  const results = q.trim()
    ? await matchPeople({ query: q, offices: office ? [office as Office] : undefined, preferAvailable: available === "1", limit: 24 })
    : [];
  const team = suggestTeam(results, teamSize);
  const bench = results.filter((r) => !team.includes(r));

  return (
    <Shell>
      <PageHeader dark eyebrow="Find a team" title={<>Who should be <span className="mark">on this?</span></>} intro="Paste the brief, the pitch email, or just a few words. We rank people on skills, project history, client verticals, role and interests – and explain why.">
        <FindForm q={q} office={office} available={available === "1"} size={teamSize} examples={examples} />
      </PageHeader>

      {q.trim() && (
        <section className="mx-auto max-w-7xl px-5 py-12">
          {results.length === 0 ? (
            <p className="text-ink/60">No strong matches. Try describing the work in different words – skills, channels, verticals, tools.</p>
          ) : (
            <>
              <div className="flex items-end justify-between mb-6">
                <h2 className="headline">Suggested <span className="serif-i">team</span></h2>
                <p className="text-sm text-mist">One per discipline first, then best overall</p>
              </div>
              <div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
                {team.map((r, i) => <ResultCard key={r.person.id} r={r} rank={i + 1} />)}
              </div>
              {bench.length > 0 && (
                <>
                  <h2 className="headline mt-14 mb-6">Also <span className="serif-i">consider</span></h2>
                  <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
                    {bench.map((r) => (
                      <Link key={r.person.id} href={`/people/${r.person.slug}`} className="card p-4 flex gap-3 items-start">
                        <Avatar person={r.person} size={44} />
                        <div className="min-w-0">
                          <p className="font-medium truncate">{fullName(r.person)} <span className="text-mist text-xs font-normal">· {r.score}</span></p>
                          <p className="text-xs text-ink/60 truncate">{r.person.title} · {officeLabel[r.person.office]}</p>
                          {r.reasons[0] && <p className="text-xs text-soul-deep mt-1 truncate">{r.reasons[0]}</p>}
                        </div>
                      </Link>
                    ))}
                  </div>
                </>
              )}
            </>
          )}
        </section>
      )}
    </Shell>
  );
}

function ResultCard({ r, rank }: { r: Awaited<ReturnType<typeof matchPeople>>[number]; rank: number }) {
  return (
    <Link href={`/people/${r.person.slug}`} className="card p-5 flex flex-col gap-4">
      <div className="flex items-start gap-4">
        <Avatar person={r.person} size={64} />
        <div className="min-w-0 flex-1">
          <p className="eyebrow">#{rank} · fit {r.score}</p>
          <p className="text-lg font-medium leading-tight">{fullName(r.person)}</p>
          <p className="text-sm text-ink/70">{r.person.title}</p>
          <p className="text-xs text-mist">{r.person.department} · {officeLabel[r.person.office]} · {r.activeProjects} live project{r.activeProjects === 1 ? "" : "s"}</p>
        </div>
      </div>
      <ul className="space-y-1 text-sm">
        {r.reasons.map((x) => <li key={x} className="flex gap-2"><span className="text-soul">■</span><span>{x}</span></li>)}
      </ul>
      {r.matchedProjects.length > 0 && (
        <div className="text-xs text-ink/60 border-t border-line pt-3">
          {r.matchedProjects.map((p) => <p key={p.name} className="truncate">{p.client ? `${p.client}: ` : ""}{p.name}{p.role ? ` (${p.role})` : ""}</p>)}
        </div>
      )}
    </Link>
  );
}
