import React from "react";
import SearchHero, { SearchBarSection } from "@/sections/search/SaearchHero";
import SearchContentGrid from "@/sections/search/SearchContentGrid";
import { fetchPropertiesWithPagination } from "@/utils/strapi";

/** Filters come from `searchParams` — this route is always request-time dynamic. */
export const dynamic = "force-dynamic";

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

const SearchPage = async ({ searchParams }: SearchPageProps) => {
  const params = await searchParams;
  const { type, location, status, size, q, page } = params;
  
  const currentPage = parseInt(page || "1", 10);
  const pageSize = 9;

  // Map filter values from URL to API format
  const mapPropertyType = (value?: string): string => {
    if (!value || value === "All") return "all";
    return value.toLowerCase();
  };

  const mapStatus = (value?: string): string => {
    if (!value || value === "All") return "all";
    // Map display values to API enum values
    const statusMap: Record<string, string> = {
      Upcoming: "upcoming",
      Ongoing: "ongoing",
      Completed: "completed",
    };
    return statusMap[value] || value.toLowerCase();
  };

  const mapLocation = (value?: string): string => {
    if (!value || value === "All") return "all";
    // Location should be slug, but constants use display names
    // We'll need to fetch locations and map them, or use slug directly
    return value.toLowerCase();
  };

  const mapSize = (value?: string): string => {
    if (!value || value === "All") return "all";
    // Size filter format - keep as is for now, API may need adjustment
    return value;
  };

  // Fetch properties with filters and pagination
  const { properties, total } = await fetchPropertiesWithPagination(
    mapPropertyType(type),
    {
      location: mapLocation(location),
      status: mapStatus(status),
      size: mapSize(size),
      searchQuery: q || "",
      page: currentPage,
      pageSize: pageSize,
    }
  );

  return (
    <>
      <SearchHero />
      <SearchBarSection />
      <SearchContentGrid
        properties={properties}
        totalItems={total}
        currentPage={currentPage}
        itemsPerPage={pageSize}
      />
    </>
  );
};

export default SearchPage;
