import { notFound } from "next/navigation";
import Link from "next/link";
import { Shell } from "@/components/Shell";
import { PageHeader } from "@/components/PageHeader";
import { db, educationResources, people, personSkills, skills } from "@/db";
import { and, eq, gte, ilike, inArray } from "drizzle-orm";
import { specialties } from "@content/education";

const kindIcon: Record<string, string> = { library: "▤", ebook: "▭", video: "▶", course: "◆", article: "≡", podcast: "◉" };

export default async function SpecialtyPage({ params }: { params: Promise<{ specialty: string }> }) {
  const { specialty } = await params;
  const key = decodeURIComponent(specialty);
  const meta = specialties.find((s) => s.key === key);
  if (!meta) notFound();
  const resources = await db.query.educationResources.findMany({ where: eq(educationResources.specialty, key), orderBy: (r, { desc, asc }) => [desc(r.featured), asc(r.kind), asc(r.title)] });
  const kinds = [...new Set(resources.map((r) => r.kind))];
  const expertIds = db.select({ id: personSkills.personId }).from(personSkills).innerJoin(skills, eq(skills.id, personSkills.skillId)).where(and(ilike(skills.name, `%${key.split(" ")[0]}%`), gte(personSkills.level, 4)));
  const experts = await db.query.people.findMany({ where: and(eq(people.isActive, true), inArray(people.id, expertIds)), limit: 6 });
  return (
    <Shell>
      <PageHeader eyebrow={<><Link href="/education" className="hover:text-ink">Education</Link> · {key}</> } title={<>{key} <span className="serif-i">library</span></>} intro={meta.blurb} />
      <section className="mx-auto max-w-7xl px-5 pb-16 grid gap-12 lg:grid-cols-[2fr_1fr]">
        <div className="space-y-10">
          {kinds.map((k) => (
            <div key={k}>
              <h2 className="eyebrow mb-3">{k === "ebook" ? "Ebooks" : k.charAt(0).toUpperCase() + k.slice(1) + (k.endsWith("y") ? "" : "s")}</h2>
              <ul className="divide-y divide-line border-t border-line">
                {resources.filter((r) => r.kind === k).map((r) => (
                  <li key={r.id}>
                    <a href={r.url} target="_blank" rel="noreferrer" className="flex gap-4 py-4 hover:text-soul">
                      <span className="text-soul text-lg leading-none mt-0.5">{kindIcon[r.kind] ?? "•"}</span>
                      <span className="flex-1"><span className="font-medium">{r.title}</span>{r.description && <span className="block text-sm text-ink/60">{r.description}</span>}</span>
                      <span className="text-xs text-mist self-center">{r.source} ↗</span>
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          ))}
          {resources.length === 0 && <p className="text-ink/60">Nothing here yet. Add resources in the database or ask an editor.</p>}
        </div>
        <aside>
          <h3 className="eyebrow mb-3">People to ask</h3>
          <ul className="space-y-2">
            {experts.map((p) => <li key={p.id}><Link href={`/people/${p.slug}`} className="text-sm hover:text-soul"><span className="font-medium">{p.firstName} {p.lastName}</span> <span className="text-mist">· {p.title}</span></Link></li>)}
          </ul>
        </aside>
      </section>
    </Shell>
  );
}
