import Link from "next/link";
import { notFound } from "next/navigation";
import { prisma } from "@/lib/prisma";
import { PropertyCard } from "@/components/PropertyCard";
import { PROPERTY_TYPE_LABELS } from "@/lib/labels";

export default async function AreaGuideDetailPage({ params }: { params: Promise<{ area: string }> }) {
  const { area: areaParam } = await params;
  const areaName = decodeURIComponent(areaParam);

  const area = await prisma.area.findUnique({ where: { name: areaName } });
  if (!area) notFound();

  const properties = await prisma.property.findMany({
    where: { areaId: area.id, status: { in: ["ACTIVE", "UNDER_OFFER"] } },
    include: {
      area: true,
      broker: true,
      amenities: true,
      photos: { where: { isHero: true }, take: 1 },
      _count: { select: { photos: true } },
    },
    orderBy: { dateListed: "desc" },
  });

  const countByType = properties.reduce<Record<string, number>>((acc, p) => {
    acc[p.type] = (acc[p.type] ?? 0) + 1;
    return acc;
  }, {});

  return (
    <main className="mx-auto max-w-6xl px-6 py-14">
      <nav className="mb-6 text-sm text-stone-400">
        <Link href="/area-guides" className="hover:text-brand">
          Area Guides
        </Link>{" "}
        / <span className="text-stone-600">{area.name}</span>
      </nav>

      <p className="text-xs font-bold tracking-widest text-brand uppercase">
        {area.region} · {area.city}, {area.province}
      </p>
      <h1 className="mt-2 text-3xl font-bold text-[#231f20]">{area.name}</h1>
      {area.shortDescription && <p className="mt-4 max-w-[62ch] text-stone-600">{area.shortDescription}</p>}

      <div className="mt-6 flex flex-wrap gap-3">
        {Object.entries(countByType).map(([type, count]) => (
          <Link
            key={type}
            href={`/properties?area=${encodeURIComponent(area.name)}&type=${type}`}
            className="rounded-full border border-stone-200 bg-white px-4 py-1.5 text-sm font-semibold text-stone-600 hover:border-brand hover:text-brand"
          >
            {count} {PROPERTY_TYPE_LABELS[type]}
          </Link>
        ))}
      </div>

      <div className="mt-10">
        {properties.length > 0 ? (
          <div className="flex flex-col gap-6">
            {properties.map((p) => (
              <PropertyCard key={p.id} property={p} />
            ))}
          </div>
        ) : (
          <div className="rounded border border-dashed border-stone-300 bg-white p-10 text-center text-stone-500">
            No active listings in {area.name} right now.{" "}
            <Link href="/contact" className="font-semibold text-brand hover:text-brand-deep">
              Contact a broker
            </Link>{" "}
            to be notified when one comes up.
          </div>
        )}
      </div>
    </main>
  );
}
