import { createServerSupabase } from "@chowrest/db/server";
import { Filters } from "./_filters";
import { ListingsView } from "./_listings-view";

export const dynamic = "force-dynamic";

const PER_PAGE = 24;

type Search = {
  q?: string;
  type?: string;
  beds?: string;
  min?: string;
  max?: string;
};

export default async function Home({
  searchParams,
}: {
  searchParams: Promise<Search>;
}) {
  const sp = await searchParams;
  const supabase = await createServerSupabase();

  let q = supabase
    .from("properties")
    .select(
      "id, title, price, type, bedrooms, bathrooms, area_sqm, city, province, images, featured, special_deal, special_deal_label, status, lat, lng",
    )
    .eq("status", "for_sale");

  if (sp.q && sp.q.trim()) {
    const term = `%${sp.q.trim()}%`;
    q = q.or(
      `title.ilike.${term},description.ilike.${term},city.ilike.${term},province.ilike.${term}`,
    );
  }
  if (sp.type) q = q.eq("type", sp.type);
  if (sp.beds) q = q.gte("bedrooms", Number(sp.beds));
  if (sp.min) q = q.gte("price", Number(sp.min));
  if (sp.max) q = q.lte("price", Number(sp.max));

  const { data } = await q
    .order("featured", { ascending: false })
    .order("created_at", { ascending: false })
    .limit(PER_PAGE);

  const listings = data ?? [];

  const { data: typeRows } = await supabase
    .from("properties")
    .select("type")
    .eq("status", "for_sale");
  const types = Array.from(
    new Set((typeRows ?? []).map((r) => r.type).filter(Boolean)),
  ).sort();

  const countLabel =
    listings.length === 0
      ? "No properties match these filters"
      : `${listings.length} propert${listings.length === 1 ? "y" : "ies"}${
          listings.length === PER_PAGE ? " · showing first 24" : ""
        }`;

  return (
    <>
      <section className="mx-auto flex max-w-site flex-wrap items-end justify-between gap-6 px-7 pt-12 pb-6">
        <div>
          <h1 className="text-[clamp(40px,5vw,60px)] font-light tracking-tightish leading-[1.05]">
            Properties{" "}
            <em className="font-normal italic text-accent">for sale</em>
          </h1>
          <p className="mt-2 text-[15px] text-text-muted">{countLabel}</p>
        </div>
      </section>

      <Filters types={types} initial={sp} />

      {listings.length === 0 ? (
        <div className="mx-auto max-w-site px-7 pb-20">
          <p className="mt-12 text-center text-[15px] text-text-muted">
            No listings match these filters.{" "}
            <a href="/" className="text-accent underline">
              Clear
            </a>
            .
          </p>
        </div>
      ) : (
        <ListingsView listings={listings} />
      )}
    </>
  );
}
