import Link from "next/link";
import { Shell } from "@/components/Shell";
import { db, people, showcaseItems, caseStudies, projects } from "@/db";
import { and, count, desc, eq, isNotNull } from "drizzle-orm";
import { nav } from "@/lib/nav";
import { PersonCard } from "@/components/PersonCard";
import { auth } from "@/auth";

export default async function Home() {
  const session = await auth();
  const firstName = session?.user?.name?.split(" ")[0] ?? "there";
  const [newest, showcase, studies, [{ staff }], [{ total }], [{ active }]] = await Promise.all([
    db.query.people.findMany({ where: and(eq(people.isActive, true), isNotNull(people.startedAt)), orderBy: desc(people.startedAt), limit: 4, with: { skills: { with: { skill: true }, limit: 4 } } }),
    db.query.showcaseItems.findMany({ orderBy: desc(showcaseItems.createdAt), limit: 3, with: { author: true } }),
    db.query.caseStudies.findMany({ where: eq(caseStudies.published, true), orderBy: desc(caseStudies.year), limit: 2 }),
    db.select({ staff: count() }).from(people).where(eq(people.isActive, true)),
    db.select({ total: count() }).from(projects),
    db.select({ active: count() }).from(projects).where(eq(projects.status, "Active")),
  ]);

  return (
    <Shell>
      <section className="grain bg-ink text-white">
        <div className="mx-auto max-w-7xl px-5 pt-16 pb-20 grid gap-10 lg:grid-cols-[1.4fr_1fr] items-end">
          <div>
            <p className="eyebrow text-white/60">Hi {firstName}</p>
            <h1 className="display mt-4">
              Look past what we sell.
              <br />
              <span className="mark">Move a soul today.</span>
            </h1>
            <p className="mt-6 max-w-xl text-white/70 text-lg">
              Everything about how CP works – the people, the work, the playbook – in one place. Independent since 1999 and still owned by the people in this building.
            </p>
            <form action="/find" className="mt-8 flex max-w-xl gap-2">
              <input name="q" placeholder="Describe a pitch or project… e.g. 'hospitality booking app, Boston, video'" className="flex-1 rounded-full bg-white/10 border border-white/15 px-5 py-3 text-sm placeholder:text-white/40 focus:outline-none focus:border-soul" />
              <button className="btn btn-soul">Find the team</button>
            </form>
          </div>
          <dl className="grid grid-cols-3 gap-4 lg:grid-cols-1">
            {[[staff, "makers, thinkers & doers"], [total, "projects in the archive"], [active, "live right now"]].map(([n, l]) => (
              <div key={String(l)} className="border-l border-white/20 pl-4">
                <dt className="text-4xl lg:text-5xl font-medium tracking-tight">{n}</dt>
                <dd className="text-sm text-white/60">{l}</dd>
              </div>
            ))}
          </dl>
        </div>
      </section>

      <section className="mx-auto max-w-7xl px-5 py-14">
        <div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
          {nav.map((n, i) => (
            <Link key={n.href} href={n.href} className="card group p-6 flex flex-col justify-between min-h-36">
              <span className="eyebrow">0{i + 1}</span>
              <div>
                <p className="text-xl font-medium group-hover:text-soul transition-colors">{n.label} →</p>
                <p className="text-sm text-ink/60 mt-1">{n.blurb}</p>
              </div>
            </Link>
          ))}
        </div>
      </section>

      <section className="mx-auto max-w-7xl px-5 py-6 grid gap-12 lg:grid-cols-[1fr_1fr]">
        <div>
          <div className="flex items-end justify-between mb-5">
            <h2 className="headline">New <span className="serif-i">faces</span></h2>
            <Link href="/people" className="text-sm underline underline-offset-4 decoration-soul">All people</Link>
          </div>
          <div className="grid gap-3 sm:grid-cols-2">
            {newest.map((p) => <PersonCard key={p.id} person={p} skills={p.skills.map((s) => s.skill.name)} />)}
          </div>
        </div>
        <div>
          <div className="flex items-end justify-between mb-5">
            <h2 className="headline">From the <span className="serif-i">showcase</span></h2>
            <Link href="/showcase" className="text-sm underline underline-offset-4 decoration-soul">See all</Link>
          </div>
          <div className="space-y-3">
            {showcase.map((s) => (
              <Link key={s.id} href={`/showcase/${s.slug}`} className="card block p-5">
                <div className="flex items-center gap-2 mb-2">
                  <span className="chip chip-soul">{s.discipline}</span>
                  <span className="chip">{s.kind.toLowerCase()}</span>
                </div>
                <p className="text-lg font-medium">{s.title}</p>
                <p className="text-sm text-ink/70 mt-1">{s.blurb}</p>
                {s.author && <p className="text-xs text-mist mt-2">by {s.author.firstName} {s.author.lastName}</p>}
              </Link>
            ))}
          </div>
          <div className="mt-8">
            <h3 className="eyebrow mb-3">Latest case studies</h3>
            {studies.map((c) => (
              <Link key={c.id} href={`/case-studies/${c.slug}`} className="block py-3 border-t border-line hover:text-soul">
                <span className="font-medium">{c.title}</span> <span className="text-mist text-sm">— {c.clientName}, {c.year}</span>
              </Link>
            ))}
          </div>
        </div>
      </section>
    </Shell>
  );
}
