import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/db/prisma";

const modules = ["artikel", "project", "galeri", "kegiatan", "prestasi-siswa"] as const;
type Module = typeof modules[number];
type Card = { id: string; title: string; description: string | null; media: string | null; href: string | null; meta: string };
type Props = { params: Promise<{ module: string }>; searchParams: Promise<{ q?: string; page?: string; category?: string; year?: string; level?: string; className?: string; technology?: string; competition?: string }> };
const perPage = 9;

function isModule(value: string): value is Module { return modules.includes(value as Module); }

export const dynamic = "force-dynamic";

export default async function ContentListPage({ params, searchParams }: Props) {
  const { module } = await params;
  if (!isModule(module)) notFound();
  const query = await searchParams;
  const q = query.q?.trim().slice(0, 100) ?? "";
  const page = Math.max(1, Number.parseInt(query.page ?? "1", 10) || 1);
  const skip = (page - 1) * perPage;
  let cards: Card[] = [];
  let total = 0;

  if (module === "artikel") {
    const where = { status: "PUBLISHED" as const, ...(q ? { OR: [{ title: { contains: q } }, { excerpt: { contains: q } }] } : {}), ...(query.category ? { category: { slug: query.category } } : {}) };
    const [rows, count] = await Promise.all([prisma.article.findMany({ where, include: { category: true }, orderBy: { publishedAt: "desc" }, skip, take: perPage }), prisma.article.count({ where })]);
    cards = rows.map((row) => ({ id: row.id, title: row.title, description: row.excerpt, media: row.cover, href: `/artikel/${row.slug}`, meta: row.category.name })); total = count;
  } else if (module === "project") {
    const year = Number(query.year) || undefined; const where = { status: "PUBLISHED" as const, ...(q ? { OR: [{ title: { contains: q } }, { description: { contains: q } }] } : {}), ...(year ? { year } : {}), ...(query.category ? { category: { slug: query.category } } : {}), ...(query.className ? { class: { name: { contains: query.className } } } : {}), ...(query.technology ? { technologies: { array_contains: query.technology } } : {}) };
    const [rows, count] = await Promise.all([prisma.project.findMany({ where, include: { class: true }, orderBy: { updatedAt: "desc" }, skip, take: perPage }), prisma.project.count({ where })]);
    cards = rows.map((row) => ({ id: row.id, title: row.title, description: row.description, media: row.thumbnail, href: `/project/${row.slug}`, meta: `${row.class.name} · ${row.year}` })); total = count;
  } else if (module === "prestasi-siswa") {
    const year = Number(query.year) || undefined; const level = ["SCHOOL", "CITY", "PROVINCE", "NATIONAL", "INTERNATIONAL"].includes(query.level ?? "") ? query.level as "SCHOOL"|"CITY"|"PROVINCE"|"NATIONAL"|"INTERNATIONAL" : undefined;
    const where = { ...(q ? { OR: [{ name: { contains: q } }, { studentName: { contains: q } }, { competition: { contains: q } }] } : {}), ...(query.competition ? { competition: { contains: query.competition } } : {}), ...(query.className ? { className: { contains: query.className } } : {}), ...(year ? { year } : {}), ...(level ? { level } : {}) };
    const [rows, count] = await Promise.all([prisma.achievement.findMany({ where, orderBy: { year: "desc" }, skip, take: perPage }), prisma.achievement.count({ where })]);
    cards = rows.map((row) => ({ id: row.id, title: row.name, description: row.description, media: row.photo, href: null, meta: `${row.studentName} · ${row.rank} · ${row.level}` })); total = count;
  } else if (module === "galeri") {
    const where = { ...(q ? { OR: [{ title: { contains: q } }, { description: { contains: q } }] } : {}), ...(query.category ? { category: query.category } : {}) };
    const [rows, count] = await Promise.all([prisma.gallery.findMany({ where, orderBy: { date: "desc" }, skip, take: perPage }), prisma.gallery.count({ where })]);
    cards = rows.map((row) => ({ id: row.id, title: row.title, description: row.description, media: row.cover, href: `/galeri/${row.slug}`, meta: `${row.category} · ${row.date.getFullYear()}` })); total = count;
  } else {
    const where = { ...(q ? { OR: [{ title: { contains: q } }, { description: { contains: q } }] } : {}), ...(query.category ? { category: query.category } : {}) };
    const [rows, count] = await Promise.all([prisma.activity.findMany({ where, orderBy: { date: "desc" }, skip, take: perPage }), prisma.activity.count({ where })]);
    cards = rows.map((row) => ({ id: row.id, title: row.title, description: row.description, media: row.cover, href: `/kegiatan/${row.slug}`, meta: `${row.category} · ${row.date.getFullYear()}` })); total = count;
  }

  const pages = Math.max(1, Math.ceil(total / perPage));
  const href = (target: number) => { const params = new URLSearchParams(); if (q) params.set("q", q); for (const key of ["category", "year", "level", "className", "technology", "competition"] as const) if (query[key]) params.set(key, query[key]); params.set("page", String(target)); return `/${module}?${params}`; };
  return <main className="mx-auto min-h-[70vh] max-w-7xl px-5 py-20 sm:px-8"><p className="text-xs font-bold uppercase tracking-widest text-emerald-600">WEBKU</p><h1 className="mt-3 text-4xl font-black capitalize sm:text-5xl">{module.replaceAll("-", " ")}</h1><form className="mt-8 grid gap-3 sm:grid-cols-4"><input name="q" defaultValue={q} placeholder="Cari konten..." className="h-11 rounded-xl border bg-white px-4 sm:col-span-2 dark:bg-slate-900" /><input name="category" defaultValue={query.category} placeholder="Kategori" className="h-11 rounded-xl border bg-white px-4 dark:bg-slate-900" />{module === "prestasi-siswa" ? <select name="level" defaultValue={query.level ?? ""} className="h-11 rounded-xl border bg-white px-3 dark:bg-slate-900"><option value="">Semua tingkat</option>{["SCHOOL","CITY","PROVINCE","NATIONAL","INTERNATIONAL"].map((level) => <option key={level}>{level}</option>)}</select> : <input name="year" type="number" defaultValue={query.year} placeholder="Tahun" className="h-11 rounded-xl border bg-white px-4 dark:bg-slate-900" />}<button className="rounded-xl bg-emerald-500 px-5 py-2 font-bold text-white">Terapkan filter</button></form><p className="mt-6 text-sm text-slate-500">{total} konten ditemukan</p><div className="mt-6 grid gap-5 md:grid-cols-2 lg:grid-cols-3">{cards.map((card) => { const content = <article className="h-full overflow-hidden rounded-2xl border bg-white dark:bg-slate-900">{card.media && <Image src={card.media} alt="" width={640} height={360} unoptimized className="aspect-video w-full object-cover" />}<div className="p-6"><p className="text-xs font-bold text-emerald-600">{card.meta}</p><h2 className="mt-2 text-xl font-bold">{card.title}</h2>{card.description && <p className="mt-3 line-clamp-3 text-sm text-slate-500">{card.description}</p>}</div></article>; return card.href ? <Link key={card.id} href={card.href}>{content}</Link> : <div key={card.id}>{content}</div>; })}</div>{!cards.length && <p className="mt-10 border-y border-dashed py-12 text-center text-slate-500">Belum ada konten yang cocok.</p>}<nav aria-label="Paginasi" className="mt-10 flex items-center justify-center gap-4">{page > 1 && <Link href={href(page - 1)} className="rounded-xl border px-4 py-2 font-semibold">Sebelumnya</Link>}<span className="text-sm text-slate-500">Halaman {Math.min(page, pages)} dari {pages}</span>{page < pages && <Link href={href(page + 1)} className="rounded-xl border px-4 py-2 font-semibold">Berikutnya</Link>}</nav></main>;
}
