import type { Metadata } from "next";

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

const defaultImage = config.APP_CONFIG.DEFAULT_IMG;

export const revalidate = 3600; // 1 hour cache

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

/* ---------------- Helpers ---------------- */

const formatSlugToTitle = (slug?: string) =>
  slug ? `10 Best ${slug.replace(/-sp-|-and-/g, " ")} 2025 in the US`
    : "Category";

const getFallbackSku = (seed: number) =>
  (globalThis.crypto?.randomUUID?.() ??
    `subcat-${seed}-${Math.random().toString(36).slice(2, 10)}`);

const normalizeProducts = (products?: any[]) =>
  Array.isArray(products)
    ? products.map((p, i) => ({
      sku: p?.sku || p?.id || getFallbackSku(i),
      title_string: p?.title_string || p?.product_name || "",
      product_name: p?.product_name || p?.title_string || "",
      brand: p?.brand || "Unknown",
      category_display: p?.category_display || p?.category || "",
      description_string: p?.description_string || "",
      price: Number(p?.price ?? 0),
      image_small: p?.image_small || p?.image_zoom || defaultImage,
      redirect_url_new: p?.redirect_url_new || p?.redirect_url || "#",
      link_string: p?.link_string || p?.merchant || "",
      feature: p?.feature,
    }))
    : [];

const normalizeRelatedProducts = (products?: any[]) =>
  Array.isArray(products)
    ? products.map((p, i) => ({
      sku: p?.sku || p?.id || getFallbackSku(i + 1000),
      title_string: p?.title_string || p?.product_name || "",
      product_name: p?.product_name || p?.title_string || "",
      brand: p?.brand || "Unknown",
      category_display: p?.category_display || p?.category || "",
      description_string: p?.description_string || "",
      price: Number(p?.price ?? 0),
      image_small: p?.image_small || p?.image_zoom || defaultImage,
      redirect_url_new: p?.redirect_url_new || p?.redirect_url || "#",
      link_string: p?.link_string || p?.merchant || "",
    }))
    : [];

/* --------- In-memory cache (prevents double API calls) --------- */
const cachedSubcatData: Record<string, any> = {};

async function loadSubcategory(slug: string) {
  if (!cachedSubcatData[slug]) {
    cachedSubcatData[slug] =
      await getShoppingGuideSubcategoryDataServer(slug);
  }
  return cachedSubcatData[slug];
}

/* ---------------- Metadata ---------------- */
export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { slug } = await params;

  // Convert slug → readable title
  const readableTitle = decodeCategorySlug(slug);

  // Warm cache (no duplicate fetch later)
  await loadSubcategory(slug);

  return {
    title: `Shopping Guide | ${readableTitle}`,
    description: `Explore top products and comparisons for ${readableTitle}.`,
    openGraph: {
      title: `Shopping Guide | ${readableTitle}`,
      description: `Find the best reviews, deals and buying guides for ${readableTitle}.`,
      type: "website",
    },
  };
}

/* ---------------- Page (SSR) ---------------- */
export default async function SubCategoryPage({ params }: Props) {
  const { slug } = await params;
  const data = await loadSubcategory(slug);

  const pageTitle = formatSlugToTitle(slug);

  const searchResults = normalizeProducts(data?.top_products);
  const relatedProducts = normalizeRelatedProducts(data?.related_products);

  const hasRelated = relatedProducts.length > 0;

  // commented as we  made this server side rendered ( using it directly in the ShoppingGuideLayout  )
  // async function handlePurchaseClick(_: any, product: any) {
  //   const currentUrl =
  //     typeof window !== "undefined" ? window.location.href : undefined;
  //   await redirectWithLander(product?.sku, currentUrl);
  // }

  return (
    <ShoppingGuideLayout
      title={pageTitle}
      showSearch={false}
      showCategories={false}
      showSearchResults
      searchResultsData={searchResults}
      searchResultsLoading={false}
      // handlePurchaseClick={handlePurchaseClick}
      showPromoted={hasRelated}
      promotedProducts={hasRelated ? relatedProducts : []}
      promotedLoading={false}
      promotedTitle="Related Products"
    />
  );
}
