import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { PropertyCard } from "@/components/PropertyCard";

export default async function HomePage() {
  const [featured, areas, activeProperties] = await Promise.all([
    prisma.property.findMany({
      where: { status: "ACTIVE" },
      include: {
        area: true,
        broker: true,
        amenities: true,
        photos: { where: { isHero: true }, take: 1 },
        _count: { select: { photos: true } },
      },
      orderBy: { dateListed: "desc" },
      take: 3,
    }),
    prisma.area.findMany({ orderBy: { name: "asc" } }),
    prisma.property.findMany({ where: { status: "ACTIVE" }, select: { listingType: true, area: { select: { region: true } } } }),
  ]);

  const tileCounts = {
    TO_LET: activeProperties.filter((p) => p.listingType === "TO_LET").length,
    FOR_SALE: activeProperties.filter((p) => p.listingType === "FOR_SALE").length,
  };

  const regionCounts = activeProperties.reduce<Record<string, number>>((acc, p) => {
    acc[p.area.region] = (acc[p.area.region] ?? 0) + 1;
    return acc;
  }, {});

  const regionBlurb: Record<string, string> = {
    Pretoria: "Richland's home base — strong office and industrial coverage from the CBD out to Centurion.",
    Johannesburg: "Sandton, Rosebank and the East Rand corridor, spanning office, retail and logistics.",
  };

  return (
    <main>
      <section className="relative overflow-hidden border-b border-stone-200 bg-[#edeae1]">
        <svg className="pointer-events-none absolute inset-0 opacity-40" width="100%" height="100%">
          <defs>
            <pattern id="blueprint" width="42" height="42" patternUnits="userSpaceOnUse">
              <path d="M42 0H0V42" fill="none" stroke="#3985b0" strokeWidth="1" opacity="0.16" />
            </pattern>
          </defs>
          <rect width="100%" height="100%" fill="url(#blueprint)" />
        </svg>
        <div className="relative mx-auto max-w-6xl px-6 py-16 sm:py-20">
          <div className="max-w-xl">
            <p className="text-xs font-bold tracking-widest text-brand uppercase">
              Commercial &amp; Industrial Property — Gauteng and beyond
            </p>
            <h1 className="mt-3 text-[2.2rem] leading-[1.08] font-bold text-balance text-[#231f20] sm:text-[2.8rem]">
              Find the right space for what your business does next.
            </h1>
            <p className="mt-4 max-w-[54ch] text-[1.05rem] text-stone-600">
              Richland Properties connects tenants, buyers and investors with office, industrial and retail
              listings across South Africa — backed by brokers who know each region on the ground.
            </p>
          </div>

          <form action="/properties" className="mt-8 rounded border border-stone-200 bg-white p-5 shadow-sm">
            <div className="grid grid-cols-1 gap-3 sm:grid-cols-4">
              <Field label="Property type">
                <select name="type" className={selectClass}>
                  <option value="">Any type</option>
                  <option value="OFFICE">Office</option>
                  <option value="INDUSTRIAL">Industrial</option>
                  <option value="RETAIL">Retail</option>
                </select>
              </Field>
              <Field label="Looking to">
                <select name="listingType" className={selectClass}>
                  <option value="">To let or buy</option>
                  <option value="TO_LET">To Let</option>
                  <option value="FOR_SALE">For Sale</option>
                </select>
              </Field>
              <Field label="Area">
                <select name="area" className={selectClass}>
                  <option value="">All areas</option>
                  {areas.map((a) => (
                    <option key={a.id} value={a.name}>
                      {a.name}
                    </option>
                  ))}
                </select>
              </Field>
              <button type="submit" className="self-end rounded bg-brand px-6 py-2.5 text-sm font-bold text-white hover:bg-brand-deep">
                Search listings
              </button>
            </div>
          </form>
        </div>
      </section>

      <div className="mx-auto mt-10 grid max-w-6xl grid-cols-1 gap-3.5 px-6 sm:grid-cols-2">
        <QuickTile href="/properties?listingType=TO_LET" label="To Let" count={tileCounts.TO_LET} />
        <QuickTile href="/properties?listingType=FOR_SALE" label="For Sale" count={tileCounts.FOR_SALE} />
      </div>

      <section className="mx-auto max-w-6xl px-6 py-16">
        <SectionHead eyebrow="Fresh to market" title="Featured listings" linkHref="/properties" linkLabel="View all listings" />
        <div className="flex flex-col gap-6">
          {featured.map((p) => (
            <PropertyCard key={p.id} property={p} />
          ))}
        </div>
      </section>

      <section className="border-y border-stone-200 bg-[#edeae1] py-16">
        <div className="mx-auto max-w-6xl px-6">
          <SectionHead eyebrow="Where we operate" title="Region highlights" />
          <div className="grid grid-cols-1 gap-5 sm:grid-cols-2">
            {Object.entries(regionCounts).map(([region, count]) => (
              <Link
                key={region}
                href={`/properties?region=${encodeURIComponent(region)}`}
                className="block rounded border border-stone-200 bg-white p-6 hover:border-brand"
              >
                <div className="text-3xl font-bold tabular-nums text-brand">
                  {count}
                  <span className="ml-1.5 text-base font-semibold text-stone-400">listings</span>
                </div>
                <h3 className="mt-1.5 font-bold text-[#231f20]">{region}</h3>
                <p className="mt-2 text-sm text-stone-600">{regionBlurb[region]}</p>
              </Link>
            ))}
          </div>
        </div>
      </section>

      <section className="mx-auto max-w-6xl px-6 py-16">
        <SectionHead eyebrow="How we help" title="Services" />
        <div className="grid grid-cols-1 gap-5 sm:grid-cols-3">
          <ServiceCard title="Brokerage &amp; Leasing" desc="End-to-end representation for landlords and tenants across office, industrial and retail leasing." />
          <ServiceCard title="Tenant Solutions" desc="Site selection, lease renegotiation and portfolio strategy for growing or relocating businesses." />
          <ServiceCard title="Investor &amp; Developer Solutions" desc="Acquisition sourcing, disposals and market intelligence for investors active in commercial property." />
        </div>
      </section>

      <section className="border-t border-stone-200 bg-[#edeae1] py-16">
        <div className="mx-auto max-w-6xl px-6">
          <div className="flex flex-wrap items-center justify-between gap-6 rounded bg-[#231f20] p-10">
            <div>
              <h2 className="text-2xl font-bold text-[#f2efe9]">Not sure where to start?</h2>
              <p className="mt-2 max-w-[50ch] text-[#c9c4be]">
                Tell us what your business needs and we&apos;ll match you with the broker who covers that area and property type.
              </p>
            </div>
            <Link href="/contact" className="rounded bg-brand px-6 py-3 text-sm font-bold text-white hover:bg-brand-deep">
              Speak to a broker
            </Link>
          </div>
        </div>
      </section>
    </main>
  );
}

const selectClass = "w-full rounded border border-stone-300 px-3 py-2.5 text-sm";

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <label className="flex flex-col gap-1.5">
      <span className="text-[11px] font-semibold tracking-wide text-stone-400 uppercase">{label}</span>
      {children}
    </label>
  );
}

function QuickTile({ href, label, count }: { href: string; label: string; count: number }) {
  return (
    <Link href={href} className="flex items-center justify-between rounded border border-stone-200 bg-white p-4.5 shadow-sm hover:border-brand">
      <span className="font-bold text-[#231f20]">{label}</span>
      <span className="text-sm tabular-nums text-stone-400">{count} listings</span>
    </Link>
  );
}

function SectionHead({ eyebrow, title, linkHref, linkLabel }: { eyebrow: string; title: string; linkHref?: string; linkLabel?: string }) {
  return (
    <div className="mb-8 flex flex-wrap items-end justify-between gap-6">
      <div>
        <p className="text-xs font-bold tracking-widest text-brand uppercase">{eyebrow}</p>
        <h2 className="mt-2 text-2xl font-bold text-[#231f20]">{title}</h2>
      </div>
      {linkHref && (
        <Link href={linkHref} className="text-sm font-semibold text-brand hover:text-brand-deep">
          {linkLabel} →
        </Link>
      )}
    </div>
  );
}

function ServiceCard({ title, desc }: { title: string; desc: string }) {
  return (
    <div className="border-t-[3px] border-brand pt-4.5">
      <h3 className="font-bold text-[#231f20]" dangerouslySetInnerHTML={{ __html: title }} />
      <p className="mt-2.5 text-sm text-stone-600">{desc}</p>
      <Link href="/contact" className="mt-3 inline-block text-sm font-semibold text-brand hover:text-brand-deep">
        Talk to a broker →
      </Link>
    </div>
  );
}
