import type { Metadata } from "next";
import { fetchApiJson } from "@/lib/api/fetchApiJson";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getServerLanguage } from "@/lib/i18n/server";
import { getSiteSeoMeta } from "@/lib/i18n/seo";
import { buildStorageUrl } from "@/components/main/BaseUrl";
import { buildProductJsonLd } from "@/lib/buildShopSeo";
import { SITE_URL } from "@/config/pageSeo";
import { IShopProductListing } from "@/types/types";
import ListingDetailClient from "./ListingDetailClient";

interface IListingPageProps {
  params: Promise<{ listingId: string }>;
}

type ShopInfo = { _id: string; name: string; logo?: string | null };

type ListingResponse = { listing?: IShopProductListing & { shop?: ShopInfo | string } };

function uniqueValues(values: (string | null | undefined)[]): string[] {
  return Array.from(new Set(values.filter((v): v is string => Boolean(v))));
}

async function loadListing(listingId: string) {
  const { data } = await fetchApiJson<ListingResponse>(`/shop-products/${listingId}`);
  return data?.listing ?? null;
}

export async function generateMetadata({ params }: IListingPageProps): Promise<Metadata> {
  const { listingId } = await params;
  const lang = await getServerLanguage();
  const site = getSiteSeoMeta(lang);
  const path = `/shops/listing/${listingId}`;

  const listing = await loadListing(listingId);
  const shop =
    listing?.shop && typeof listing.shop === "object" ? listing.shop : null;

  if (!listing) {
    const meta = generatePageMetadata({
      title: `کالا یافت نشد | ${site.titleSuffix}`,
      description: site.defaultDescription,
      path,
      index: false,
      lang,
    });
    return { ...meta, title: { absolute: `کالا یافت نشد | ${site.titleSuffix}` } };
  }

  const title = `${listing.title}${shop?.name ? ` - در فروشگاه (${shop.name})` : ""} | ${site.titleSuffix}`;

  const colors = uniqueValues(listing.variants?.map((v) => v.color));
  const sizes = uniqueValues(listing.variants?.map((v) => v.size));
  const weights = uniqueValues(listing.variants?.map((v) => v.weight));
  const prices = (listing.variants || []).map((v) =>
    v.discount_price != null ? v.discount_price : v.price
  );
  const cheapest = prices.length ? Math.min(...prices) : null;
  const priceText = cheapest != null ? `${cheapest.toLocaleString("fa-IR")} تومان` : "";

  const description = [
    listing.description,
    colors.length ? colors.join("، ") : null,
    sizes.length ? sizes.join("، ") : null,
    weights.length ? weights.join("، ") : null,
    priceText || null,
  ]
    .filter(Boolean)
    .join(" - ") || site.defaultDescription;

  const primaryImage = listing.images?.[listing.primaryImageIndex] || listing.images?.[0];

  const meta = generatePageMetadata({
    title,
    description,
    path,
    type: "website",
    imageUrl: primaryImage ? buildStorageUrl(primaryImage) : undefined,
    imageAlt: listing.title,
    lang,
  });

  return { ...meta, title: { absolute: title } };
}

export default async function ListingDetailPage({ params }: IListingPageProps) {
  const { listingId } = await params;
  const lang = await getServerLanguage();
  const listing = await loadListing(listingId);
  const shop =
    listing?.shop && typeof listing.shop === "object" ? listing.shop : null;

  const jsonLd = listing
    ? buildProductJsonLd(
        listing,
        shop,
        `${SITE_URL}/shops/listing/${listingId}`,
        lang
      )
    : null;

  return (
    <>
      {jsonLd && (
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
        />
      )}
      <ListingDetailClient />
    </>
  );
}
