import type { Metadata } from "next";

import ShoppingGuideLayout from "@/components/shopping-guide/ShoppingGuideLayout";
import { getShoppingGuideCategoryDataServer } from "@/services/shopping-guide.service.server";
import config from "@/utils/config";
import "../../../../styles/shopping-guide-style.css";

const defaultImage = config.APP_CONFIG.DEFAULT_IMG;

export const revalidate = 3600; // cache page for 1 hour

type Props = {
  params: Promise<{ slug: string }>;
};

// -------- Helpers --------
const topRatedKeywords = [
  "Walking Pads",
  "Mattress Toppers",
  "Printers",
  "TV Soundbars",
  "Dehumidifiers",
  "Upright Vacuums",
];

const decodeCategorySlug = (value?: string) =>
  value?.replace(/-sp--and--sp-/g, " & ").replace(/-sp-/g, " ") || "Category";

const makeSubcategorySlug = (subcategory: string) =>
  subcategory.replace(/&/g, "-and-").replace(/\s+/g, "-sp-");

const cachedCategoryData: Record<string, any> = {};

async function loadCategory(slug: string) {
  if (!cachedCategoryData[slug]) {
    cachedCategoryData[slug] =
      await getShoppingGuideCategoryDataServer(slug);
  }
  return cachedCategoryData[slug];
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;
  await loadCategory(slug);
  return {
    title: ` Shopping Guide | ${slug}`,
    description: `Explore top products, tips and comparisons for ${slug}.`,
  };
}

export default async function CategoryPage({ params }: Props) {
  const { slug } = await params;

  const data = await loadCategory(slug);

  const categoryTitle = data?.category_plain || decodeCategorySlug(slug);

  const subCategories = Object.entries(data?.sub_categories || {}).map(
    ([name, count]) => ({
      name,
      slug: makeSubcategorySlug(name),
      productCount: Number(count) || 0,
      imageUrl: defaultImage,
    })
  );

  return (
    <ShoppingGuideLayout
      title={categoryTitle}
      showSearch={false}
      showCategories={false}
      showPromoted={false}
      showSearchResults={false}
      showSubCategories={false}
      showCategorySearch={true}
      categorySearchProps={{
        categoryTitle,
        subCategories,
        topRatedKeywords,
      }}
      categorySearchLoading={false}
    />
  );
}
