import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { LayoutGrid, Map as MapIcon } from "lucide-react";
import {
  isLocale,
  isLocationSlug,
  localizedPath,
  locationSlugs,
  propertyQuerySchema,
  propertyTypes,
  type Locale,
  type LocationSlug,
  type PropertyType,
} from "@alterra/shared";
import PageHero from "@/components/PageHero";
import ClosingCta from "@/components/ClosingCta";
import PropertyCard from "@/components/properties/PropertyCard";
import PropertyFilters from "@/components/properties/PropertyFilters";
import ListingMap from "@/components/properties/ListingMap";
import { buildCrumbs } from "@/lib/breadcrumbs";
import { fetchProperties, fetchZoneCounts } from "@/lib/api";
import { fill, getPropertyCopy } from "@/lib/propertyCopy";
import { getHomeCopy } from "@/lib/home";
import { getLayoutCopy, getPageCopy, locations } from "@/lib/site";
import { pageMetadata } from "@/lib/seo";

type SearchParams = Promise<Record<string, string | string[] | undefined>>;
type Params = Promise<{ lang: string }>;

const FILTER_KEYS = [
  "zone", "type", "operation", "currency", "minPrice", "maxPrice", "minBeds",
  "minBuiltArea", "maxBuiltArea", "minLotArea", "maxLotArea", "features", "sort", "page", "view",
] as const;
const PAGE_SIZE = 12;

// Filters come from the query string, so the listing renders per request (API responses are still cached 60 s).
export const dynamic = "force-dynamic";

const readParams = async (searchParams: SearchParams) => {
  const sp = await searchParams;
  const raw: Record<string, string> = {};
  for (const key of FILTER_KEYS) {
    const value = sp[key];
    const single = Array.isArray(value) ? value[0] : value;
    if (single) raw[key] = single;
  }
  return raw;
};

/** Keeps only the filters the API accepts; an invalid value is dropped rather than breaking the page. */
const sanitize = (raw: Record<string, string>, lang: Locale) => {
  const clean: Record<string, string> = {};
  for (const [key, value] of Object.entries(raw)) {
    if (key === "view") continue;
    if (propertyQuerySchema.safeParse({ [key]: value }).success) clean[key] = value;
  }
  return { ...clean, lang };
};

const headline = (lang: Locale, zone?: string, type?: string) => {
  const l = getPropertyCopy(lang);
  const zoneName = zone && isLocationSlug(zone) ? locations[zone].name[lang] : undefined;
  const typeName = type && (propertyTypes as readonly string[]).includes(type) ? l.types[type as PropertyType] : undefined;
  if (zoneName && typeName) return fill(l.listing.typeZoneTitle, { type: typeName, zone: zoneName });
  if (zoneName) return fill(l.listing.zoneTitle, { zone: zoneName });
  if (typeName) return fill(l.listing.typeTitle, { type: typeName });
  return null;
};

export async function generateMetadata({ params, searchParams }: { params: Params; searchParams: SearchParams }): Promise<Metadata> {
  const { lang } = await params;
  if (!isLocale(lang)) return {};
  const raw = await readParams(searchParams);
  const page = getPageCopy(lang, "/properties")!;
  const title = headline(lang, raw.zone, raw.type) ?? page.title;
  const meta = pageMetadata({ lang, path: "/properties", title, description: page.description });

  // Zone and type are indexable: they are part of the canonical URL; every other filter is not.
  const indexable = new URLSearchParams();
  if (raw.zone && isLocationSlug(raw.zone)) indexable.set("zone", raw.zone);
  if (raw.type && (propertyTypes as readonly string[]).includes(raw.type)) indexable.set("type", raw.type);
  const suffix = indexable.size ? `?${indexable}` : "";
  return {
    ...meta,
    alternates: {
      canonical: `${localizedPath(lang, "/properties")}${suffix}`,
      languages: {
        en: `${localizedPath("en", "/properties")}${suffix}`,
        es: `${localizedPath("es", "/properties")}${suffix}`,
        "x-default": `${localizedPath("en", "/properties")}${suffix}`,
      },
    },
  };
}

export default async function PropertiesPage({ params, searchParams }: { params: Params; searchParams: SearchParams }) {
  const { lang } = await params;
  if (!isLocale(lang)) notFound();

  const raw = await readParams(searchParams);
  const query = sanitize(raw, lang);
  const view = raw.view === "map" ? "map" : "grid";
  const copy = getPropertyCopy(lang);
  const l = copy.listing;
  const page = getPageCopy(lang, "/properties")!;
  const home = getHomeCopy(lang);

  const [list, facets] = await Promise.all([
    fetchProperties({ ...query, pageSize: PAGE_SIZE }),
    view === "map" ? fetchZoneCounts(query) : Promise.resolve(null),
  ]);

  const basePath = localizedPath(lang, "/properties");
  const hrefWith = (overrides: Record<string, string | undefined>) => {
    const next = new URLSearchParams({ ...raw });
    for (const [key, value] of Object.entries(overrides)) {
      if (value) next.set(key, value);
      else next.delete(key);
    }
    return next.size ? `${basePath}?${next}` : basePath;
  };

  const zoneNames = Object.fromEntries(locationSlugs.map((s) => [s, locations[s].name[lang]])) as Record<LocationSlug, string>;
  const title = headline(lang, raw.zone, raw.type) ?? page.title;

  return (
    <main>
      <PageHero lang={lang} eyebrow={page.eyebrow} title={title} intro={page.description} crumbs={buildCrumbs(lang, "/properties", page.crumb)} />

      <section className="bg-cream">
        <div className="mx-auto max-w-7xl px-5 py-14 md:px-8 md:py-20">
          <PropertyFilters
            key={JSON.stringify(raw)}
            copy={copy}
            zones={locationSlugs.map((s) => ({ value: s, label: zoneNames[s] }))}
            initial={raw}
            total={list?.total ?? null}
          />

          <div className="mt-10 flex justify-end gap-2" role="group" aria-label={l.filters}>
            {(["grid", "map"] as const).map((v) => (
              <Link
                key={v}
                href={hrefWith({ view: v === "grid" ? undefined : v, page: undefined })}
                scroll={false}
                aria-current={view === v ? "true" : undefined}
                className={`flex items-center gap-2 border px-4 py-2 text-xs tracking-[0.12em] uppercase transition ${
                  view === v ? "border-ink bg-ink text-cream" : "border-ink/20 hover:border-ink"
                }`}
              >
                {v === "grid" ? <LayoutGrid size={14} strokeWidth={1.5} /> : <MapIcon size={14} strokeWidth={1.5} />}
                {v === "grid" ? l.grid : l.map}
              </Link>
            ))}
          </div>

          {view === "map" && (
            <div className="mt-8">
              <ListingMap
                counts={facets?.zones ?? {}}
                names={zoneNames}
                hrefFor={(slug) => hrefWith({ zone: raw.zone === slug ? undefined : slug, page: undefined })}
                active={raw.zone && isLocationSlug(raw.zone) ? raw.zone : undefined}
                medellin={home.zones.medellin}
                airport={home.zones.airport}
                note={home.zones.note}
                hint={l.mapHint}
              />
            </div>
          )}

          {!list ? (
            <p className="mx-auto max-w-xl py-20 text-center font-serif text-2xl text-ink/70">{l.unavailable}</p>
          ) : list.items.length === 0 ? (
            <div className="mx-auto max-w-xl py-20 text-center">
              <p className="font-serif text-2xl leading-snug text-ink/80">{l.empty}</p>
              <Link
                href={localizedPath(lang, "/contact")}
                className="mt-8 inline-block bg-ink px-7 py-3.5 text-[0.78rem] tracking-[0.14em] uppercase text-cream transition hover:bg-forest"
              >
                {l.contactAdvisor}
              </Link>
            </div>
          ) : (
            <>
              <h2 className="sr-only">{list.total === 1 ? l.resultOne : l.resultMany.replace("{n}", String(list.total))}</h2>
              <div className="mt-10 grid gap-x-8 gap-y-14 md:grid-cols-2 lg:grid-cols-3">
                {list.items.map((item, i) => (
                  <PropertyCard key={item.slug} property={item} lang={lang} copy={copy} priority={i < 3} />
                ))}
              </div>

              {list.totalPages > 1 && (
                <nav aria-label={fill(l.page, { page: list.page, total: list.totalPages })} className="mt-16 flex items-center justify-between border-t border-sand pt-8">
                  {list.page > 1 ? (
                    <Link href={hrefWith({ page: String(list.page - 1) })} className="eyebrow text-ink transition hover:text-gold-ink">
                      ← {l.previous}
                    </Link>
                  ) : (
                    <span />
                  )}
                  <span className="text-sm text-stone">{fill(l.page, { page: list.page, total: list.totalPages })}</span>
                  {list.page < list.totalPages ? (
                    <Link href={hrefWith({ page: String(list.page + 1) })} className="eyebrow text-ink transition hover:text-gold-ink">
                      {l.next} →
                    </Link>
                  ) : (
                    <span />
                  )}
                </nav>
              )}
            </>
          )}
        </div>
      </section>

      <ClosingCta lang={lang} copy={getLayoutCopy(lang)} />
    </main>
  );
}
