import { notFound } from "next/navigation";
import Link from "next/link";
import { Shell } from "@/components/Shell";
import { offices } from "@content/offices";
import { db, people } from "@/db";
import { and, asc, eq } from "drizzle-orm";
import { Avatar } from "@/components/Avatar";
import { Markdown } from "@/components/Markdown";
import type { Office } from "@/db/schema";

export const dynamic = "force-dynamic";

export default async function OfficePage({ params }: { params: Promise<{ slug: string }> }) {
  const { slug } = await params;
  const o = offices.find((x) => x.slug === slug);
  if (!o) notFound();
  const staff = await db.query.people.findMany({ where: and(eq(people.isActive, true), eq(people.office, o.city.toUpperCase() as Office)), orderBy: asc(people.lastName) });
  return (
    <Shell>
      <section className={`grain ${slug === "dublin" ? "bg-soul" : "bg-ink"} text-white`}>
        <div className="mx-auto max-w-7xl px-5 py-16">
          <p className="eyebrow text-white/70"><Link href="/offices" className="hover:text-white">Offices</Link> · {o.name}</p>
          <h1 className="display mt-3">{o.city}</h1>
          <p className="serif-i mt-4 text-2xl text-white/85 max-w-2xl">{o.hero}</p>
          <div className="mt-8 grid gap-6 sm:grid-cols-3 text-sm">
            <div><p className="text-white/60">Address</p>{o.address.map((l) => <p key={l}>{l}</p>)}<a href={o.mapUrl} target="_blank" rel="noreferrer" className="underline underline-offset-4 mt-1 inline-block">Map ↗</a></div>
            <div><p className="text-white/60">Office lead</p><p>{o.lead.name}</p><p className="text-white/80">{o.lead.title}</p><p>{o.phone}</p></div>
            <div><p className="text-white/60">Wi-Fi</p><p>{o.wifi}</p></div>
          </div>
        </div>
      </section>
      <section className="mx-auto max-w-7xl px-5 py-12 grid gap-12 lg:grid-cols-[2fr_1fr]">
        <div className="space-y-8 max-w-3xl">
          {o.sections.map((s) => (
            <div key={s.title}><h2 className="text-2xl font-medium tracking-tight mb-2">{s.title}</h2><Markdown>{s.body}</Markdown></div>
          ))}
        </div>
        <aside className="space-y-10">
          <div>
            <h3 className="eyebrow mb-3">Nearby</h3>
            <ul className="space-y-3 text-sm">{o.nearby.map((n) => <li key={n.name}><span className="font-medium">{n.name}</span> <span className="text-mist">· {n.kind}</span><br /><span className="text-ink/70">{n.note}</span></li>)}</ul>
          </div>
          <div>
            <h3 className="eyebrow mb-3">Who's based here ({staff.length})</h3>
            <div className="flex flex-wrap gap-2">
              {staff.map((p) => <Link key={p.id} href={`/people/${p.slug}`} title={`${p.firstName} ${p.lastName}`}><Avatar person={p} size={40} className="ring-2 ring-white hover:ring-soul" /></Link>)}
            </div>
          </div>
        </aside>
      </section>
    </Shell>
  );
}
