import Link from "next/link";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { prisma } from "@/lib/prisma";
import { getSettings, getSiteContentMap, site } from "@/lib/session";
import { PuertoRicoPueblosMap } from "@/components/PuertoRicoPueblosMap";
import { buildCityCounts } from "@/lib/pr-municipalities";
import { Reveal } from "@/components/motion/Reveal";

export default async function EmpleosPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string; city?: string }>;
}) {
  const settings = await getSettings();
  if (!settings.moduleJobs) redirect("/?error=Modulo%20desactivado");

  const sp = await searchParams;
  const content = await getSiteContentMap();
  const [jobs, allForCounts] = await Promise.all([
    prisma.job.findMany({
      where: {
        status: "active",
        ...(sp.q
          ? {
              OR: [
                { title: { contains: sp.q } },
                { company: { contains: sp.q } },
                { description: { contains: sp.q } },
              ],
            }
          : {}),
        ...(sp.city ? { city: { contains: sp.city } } : {}),
      },
      orderBy: { createdAt: "desc" },
      include: { _count: { select: { applicants: true } } },
    }),
    prisma.job.findMany({
      where: { status: "active" },
      select: { city: true },
    }),
  ]);

  const counts = buildCityCounts(allForCounts.map((j) => j.city));

  return (
    <div>
      <div className="mb-6 flex flex-wrap items-end justify-between gap-4">
        <div>
          <p className="text-xs tracking-wider text-[var(--lime)] uppercase">
            {site(content, "jobsLabel")}
          </p>
          <h1 className="text-3xl font-semibold">{site(content, "jobsTitle")}</h1>
          <p className="text-white/60">
            {site(content, "jobsSub")}
            {sp.city ? ` · ${sp.city}` : ""}
          </p>
        </div>
        <Link href="/empleos/nuevo" className="btn-primary">
          Publicar empleo
        </Link>
      </div>

      <form className="mb-6 flex flex-wrap gap-2">
        <input
          className="input max-w-xs"
          name="q"
          placeholder="Buscar…"
          defaultValue={sp.q || ""}
        />
        {sp.city ? <input type="hidden" name="city" value={sp.city} /> : null}
        <button className="btn-ghost" type="submit">
          Filtrar
        </button>
      </form>

      <Reveal className="mb-8">
        <Suspense
          fallback={
            <div className="pr-pueblos-map__canvas grid place-items-center text-sm text-white/45">
              Cargando mapa…
            </div>
          }
        >
          <PuertoRicoPueblosMap
            counts={counts}
            label="Filtrar empleos por pueblo"
          />
        </Suspense>
      </Reveal>

      <div className="space-y-3">
        {jobs.map((j) => (
          <Link
            key={j.id}
            href={`/empleos/${j.id}`}
            className="card flex justify-between gap-4"
          >
            <div>
              <p className="font-semibold">{j.title}</p>
              <p className="text-sm text-white/60">
                {j.company} · {j.city} · {j.salary}
              </p>
              <p className="mt-1 text-xs text-white/40">
                {j._count.applicants} aplicantes
              </p>
            </div>
            <span className="badge h-fit">{j.type.replace("_", " ")}</span>
          </Link>
        ))}
        {!jobs.length && (
          <p className="text-white/50">
            No hay empleos{sp.city ? ` en ${sp.city}` : ""} con esos filtros.
          </p>
        )}
      </div>
    </div>
  );
}
