import PageContainer from "@/sections/properties/contents";
import HeroWrapper from "@/sections/properties/hero/HeroWrapper";
import {
  fetchPropertiesWithPagination,
  fetchLocationsForListingPages,
  fetchListingPropertyPageBySlug,
  fetchPublishedListingPropertyPageSlugs,
} from "@/utils/strapi";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { getPropertyTypeHeroImages } from "@/sections/properties/hero/propertyTypeImages";
import { getStrapiImageUrl } from "@/utils/getStrapiUrl";

const BASE_URL =
  process.env.NEXT_PUBLIC_BASE_URL ||
  process.env.NEXT_PUBLIC_SITE_URL ||
  (process.env.NODE_ENV === "production"
    ? "https://navana-realestate.com"
    : "http://localhost:3000");

export async function generateMetadata({
  params,
}: PropertiesByTypePageProps): Promise<Metadata> {
  const { type } = await params;
  const normalizedType = type?.toLowerCase() || "";
  const [listingPage, publishedSlugs] = await Promise.all([
    fetchListingPropertyPageBySlug(normalizedType),
    fetchPublishedListingPropertyPageSlugs(),
  ]);
  const slugOk =
    publishedSlugs.length === 0 || publishedSlugs.includes(normalizedType);
  if (!slugOk || !listingPage) {
    return { title: "Properties | Navana Real Estate" };
  }

  const seo = listingPage.seo;
  const title =
    seo?.title ||
    `${listingPage.name} | Navana Real Estate`;
  const description =
    seo?.description ||
    `Explore ${listingPage.name} properties from Navana Real Estate.`;
  const images = getPropertyTypeHeroImages(normalizedType);
  const ogFromSeo = seo?.imageUrl ? getStrapiImageUrl(seo.imageUrl) : null;
  const ogFromHero =
    listingPage.heroDesktopBigImageUrl ||
    listingPage.heroImageMobileUrl ||
    null;
  const ogImageRaw = ogFromSeo || ogFromHero;
  const ogImage =
    ogImageRaw && ogImageRaw.startsWith("http")
      ? ogImageRaw
      : ogImageRaw
        ? getStrapiImageUrl(ogImageRaw)
        : images.right.startsWith("http")
          ? images.right
          : `${BASE_URL}${images.right}`;

  return {
    title,
    description,
    keywords: seo?.keywords ? seo.keywords.split(",").map((k) => k.trim()) : undefined,
    openGraph: {
      title,
      description,
      url: `${BASE_URL}/properties/${normalizedType}`,
      type: "website",
      images: [{ url: ogImage, width: 1200, height: 630, alt: title }],
    },
    twitter: {
      card: "summary_large_image",
      title,
      description,
      images: [ogImage],
    },
    alternates: { canonical: `${BASE_URL}/properties/${normalizedType}` },
  };
}

interface PropertiesByTypePageProps {
  params: Promise<{ type: string }>;
  searchParams: Promise<{
    location?: string;
    status?: string;
    size?: string;
    q?: string;
    page?: string;
  }>;
}

const PropertiesByType = async ({
  params,
  searchParams,
}: PropertiesByTypePageProps) => {
  const { type } = await params;
  const { location, status, size, q, page } = await searchParams;

  const normalizedType = type.toLowerCase();
  const [publishedSlugs, listingPage] = await Promise.all([
    fetchPublishedListingPropertyPageSlugs(),
    fetchListingPropertyPageBySlug(normalizedType),
  ]);
  if (
    publishedSlugs.length > 0 &&
    !publishedSlugs.includes(normalizedType)
  ) {
    notFound();
  }

  const currentPage = parseInt(page || "1", 10);
  const pageSize = 8;

  const [{ properties, total }, locations] = await Promise.all([
    fetchPropertiesWithPagination(normalizedType, {
      location: location || "all",
      status: status || "all",
      size: size || "all",
      searchQuery: q || "",
      page: currentPage,
      pageSize,
    }),
    fetchLocationsForListingPages(),
  ]);

  return (
    <>
      {currentPage === 1 && (
        <HeroWrapper type={normalizedType} listingPage={listingPage} />
      )}
      <PageContainer
        properties={properties}
        type={normalizedType}
        totalItems={total}
        currentPage={currentPage}
        pageSize={pageSize}
        locations={locations}
      />
    </>
  );
};

export default PropertiesByType;
