'use client';
import BackgroundGradients from "@/components/BackgroundGradients";
import ContactHero from "@/components/ContactHero";
import Footer from "@/components/Footer";
import ProductListing, { type ProductListingPageSize } from "@/components/ProductListing";
import type { Product } from "@/components/ProductCard";
import PageLoading from "@/components/PageLoading";
import { useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { getStoredLocale, getStoredLocaleRaw } from "@/i18n/localeSwitcher";

function toMarketplacePathSegment(value: unknown): string {
  const raw = String(value ?? "")
    .trim()
    .toLowerCase()
    .replace(/&/g, " and ")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
  return raw;
}

function isRealCategorySegment(value: string): boolean {
  const t = String(value ?? "").trim();
  return t.length > 0 && t !== "undefined" && t !== "uncategorized";
}

function collectCategoryTreePathSlugs(tree: unknown): string[] {
  const slugs: string[] = [];
  let node: unknown = tree;
  while (node && typeof node === "object" && !Array.isArray(node)) {
    const rec = node as Record<string, unknown>;
    const slug = toMarketplacePathSegment(rec.slug);
    if (isRealCategorySegment(slug)) slugs.push(slug);
    node = rec.sub_category ?? rec.subcategory ?? null;
  }
  return slugs;
}

function marketplaceProductUrlPartsFromApiItem(item: Record<string, unknown>): {
  marketplace_path_segments: string[];
  category_slug: string;
  subcategory_slug: string;
  product_slug: string;
} | null {
  const product_slug = toMarketplacePathSegment(item?.handle ?? item?.slug ?? "");
  if (!product_slug) return null;

  const treeSegments = collectCategoryTreePathSlugs(item?.category_tree);
  if (treeSegments.length > 0) {
    return {
      marketplace_path_segments: treeSegments,
      category_slug: treeSegments[0]!,
      subcategory_slug: treeSegments[1] ?? "",
      product_slug,
    };
  }

  const categoryObj =
    item?.category && typeof item.category === "object" && !Array.isArray(item.category)
      ? (item.category as Record<string, unknown>)
      : null;
  const nestedSubcategory = (categoryObj?.subcategory ?? null) as Record<string, unknown> | null;
  const categoryRaw =
    item?.category_name ??
    item?.category_label ??
    categoryObj?.name ??
    categoryObj?.label ??
    (typeof item?.category === "string" ? item.category : null) ??
    item?.category_slug ??
    item?.category_handle ??
    categoryObj?.slug ??
    categoryObj?.handle;
  const subcategoryRaw =
    item?.subcategory_name ??
    item?.sub_category_name ??
    item?.subcategory_label ??
    item?.sub_category_label ??
    nestedSubcategory?.name ??
    nestedSubcategory?.label ??
    (typeof item?.subcategory === "string" ? item.subcategory : null) ??
    item?.subcategory_slug ??
    item?.sub_category_slug ??
    item?.subcategory_handle ??
    nestedSubcategory?.slug ??
    nestedSubcategory?.handle;
  const flatSegments = [toMarketplacePathSegment(categoryRaw), toMarketplacePathSegment(subcategoryRaw)].filter(
    isRealCategorySegment,
  );
  if (flatSegments.length > 0) {
    return {
      marketplace_path_segments: flatSegments,
      category_slug: flatSegments[0]!,
      subcategory_slug: flatSegments[1] ?? "",
      product_slug,
    };
  }

  return {
    marketplace_path_segments: [],
    category_slug: "",
    subcategory_slug: "",
    product_slug,
  };
}

type SortOption = { value: string; label: string };
type SeoMeta = {
  title: string;
  description: string;
  keywords: string[];
};

function getMarketplaceSeoMeta(data: any): SeoMeta {
  const seoSection = data?.page?.sections?.find((section: any) => section.key === "seo");
  const seoComponent = seoSection?.components?.find(
    (component: any) => component?.type?.name === "seo_meta"
  );
  const seoItem = seoComponent?.instance?.data ?? {};

  const title = typeof seoItem?.title === "string" ? seoItem.title : "";
  const description = typeof seoItem?.description === "string" ? seoItem.description : "";
  const keywordsRaw = typeof seoItem?.keywords === "string" ? seoItem.keywords : "";
  const keywords = keywordsRaw
    .split(",")
    .map((keyword: string) => keyword.trim())
    .filter(Boolean);

  return { title, description, keywords };
}

function mapProductCardsSortOptions(data: unknown): SortOption[] {
  const raw = Array.isArray((data as { sort_options?: unknown })?.sort_options)
    ? (data as { sort_options: { type?: string; display_name?: string }[] }).sort_options
    : [];
  return raw
    .map((o) => ({
      value: String(o?.type ?? "").trim(),
      label: String(o?.display_name ?? o?.type ?? "").trim(),
    }))
    .filter((o) => o.value);
}

async function getMarketplaceProducts(
  page: number,
  urlQuery: string,
  pageSize: ProductListingPageSize
) {
  const base = process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL;
  if (!base) {
    return {
      products: [] as Product[],
      totalCount: 0,
      totalPages: 1,
      currentPage: page,
      sortOptions: [] as SortOption[],
    };
  }
  try {
    const params = new URLSearchParams(urlQuery);
    params.delete("limit");
    params.set("page", String(page));
    if (pageSize === "all") {
      params.set("limit", "all");
    } else if (pageSize === 16 || pageSize === 32) {
      params.set("limit", String(pageSize));
    } else {
      params.set("limit", "8");
    }
    const query = params.toString();
    const res = await fetch(`${base}/store/product-cards?${query}`, {
      method: "GET",
      headers: {
        "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
      },
      cache: "no-store",
    });
    if (!res.ok) {
      return {
        products: [] as Product[],
        totalCount: 0,
        totalPages: 1,
        currentPage: page,
        sortOptions: [] as SortOption[],
      };
    }
    const data = await res.json();
    const items = Array.isArray(data?.products) ? data.products : [];
    const total = Number(data?.total ?? 0);
    const limit = Number(data?.limit ?? data?.per_page ?? data?.page_size ?? items.length ?? 0);
    const apiTotalPages = Number(data?.total_pages ?? data?.pages ?? 0);
    const computedTotalPages = limit > 0 ? Math.ceil(total / limit) : 0;
    const resolvedTotalPages = apiTotalPages > 0 ? apiTotalPages : computedTotalPages;
    const shouldShowPagination = limit > 0 ? total > limit : resolvedTotalPages > 1;
    const products = items
      .map((item: any) => {
        const parts = marketplaceProductUrlPartsFromApiItem(item as Record<string, unknown>);
        if (!parts) return null;
        return {
          id: item.id ?? item._id ?? item.product_id ?? item.slug ?? "",
          handle: item.handle ?? "",
          marketplace_path_segments: parts.marketplace_path_segments,
          category_slug: parts.category_slug,
          subcategory_slug: parts.subcategory_slug,
          product_slug: parts.product_slug,
          image: item.image ?? "",
          subtitle: item.subtitle ?? "",
          title: item.name ?? "",
          category: item.category_label ?? "",
          location: item.location ?? "",
          available_quantity: item.available_quantity ?? "",
          code: item.code ?? "",
          price_amount: String(item.price_amount ?? ""),
          currency_symbol: item.currency_symbol ?? "",
          inStock: item.availability,
          unit: item.unit ?? "",
        };
      })
      .filter(Boolean) as Product[];
    return {
      products,
      totalCount: total,
      totalPages: shouldShowPagination ? Math.max(1, resolvedTotalPages) : 0,
      currentPage: shouldShowPagination ? Math.max(1, Number(data?.page ?? page)) : 1,
      sortOptions: mapProductCardsSortOptions(data),
    };
  } catch {
    return {
      products: [] as Product[],
      totalCount: 0,
      totalPages: 1,
      currentPage: page,
      sortOptions: [] as SortOption[],
    };
  }
}
const MARKETPLACE_ZIGZAG_COUNT = 4;

export default function MarketplacePageClient() {
  const searchParams = useSearchParams();
  const [products, setProducts] = useState<Product[]>([]);
  const [pageSize, setPageSize] = useState<ProductListingPageSize>(8);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalCount, setTotalCount] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [pageData, setPageData] = useState<any>(null);
  const [sortOptions, setSortOptions] = useState<SortOption[] | undefined>(undefined);
  const [isLoading, setIsLoading] = useState(true);
  const [seo, setSeo] = useState<SeoMeta>({
    title: "Biomket",
    description: "Biomket marketplace",
    keywords: [],
  });
  const filterQueryFromUrl = searchParams.toString();

  useEffect(() => {
    let isMounted = true;

    const loadServicesPage = async () => {
      try {
        const xMedusaLocale = (getStoredLocaleRaw() ?? getStoredLocale()).trim();
        const [res, productsData] = await Promise.all([
          fetch(`${process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL}/store/pages/marketplace`, {
            method: "GET",
            headers: {
              "x-publishable-api-key": process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_API_KEY || "",
              "x-medusa-locale": xMedusaLocale,
            },
            cache: "no-store",
          }),
          getMarketplaceProducts(currentPage, filterQueryFromUrl, pageSize),
        ]);

        if (isMounted) {
          setProducts(productsData.products);
          setTotalCount(productsData.totalCount);
          setTotalPages(productsData.totalPages);
          setCurrentPage(productsData.currentPage);
          setSortOptions(
            productsData.sortOptions.length > 0 ? productsData.sortOptions : undefined
          );
          if (res.ok) {
            const pageJson = await res.json();
            setPageData(pageJson);
            setSeo(getMarketplaceSeoMeta(pageJson));
          }
        }
      } catch {
      } finally {
        if (isMounted) setIsLoading(false);
      }
    };

    loadServicesPage();
    return () => {
      isMounted = false;
    };
  }, [currentPage, filterQueryFromUrl, pageSize]);

  useEffect(() => {
    document.title = seo.title || "Biomket";
    const descriptionContent = seo.description || "Biomket marketplace";
    let descriptionMeta = document.querySelector('meta[name="description"]');
    if (!descriptionMeta) {
      descriptionMeta = document.createElement("meta");
      descriptionMeta.setAttribute("name", "description");
      document.head.appendChild(descriptionMeta);
    }
    descriptionMeta.setAttribute("content", descriptionContent);

    const keywordsContent = seo.keywords.length > 0 ? seo.keywords.join(", ") : "";
    let keywordsMeta = document.querySelector('meta[name="keywords"]');
    if (!keywordsMeta) {
      keywordsMeta = document.createElement("meta");
      keywordsMeta.setAttribute("name", "keywords");
      document.head.appendChild(keywordsMeta);
    }
    if (keywordsContent) {
      keywordsMeta.setAttribute("content", keywordsContent);
    } else {
      keywordsMeta.removeAttribute("content");
    }
  }, [seo]);

  const sections = pageData?.page?.sections ?? [];
  const findSectionData = (...keys: string[]) => {
    const section = sections.find((s: any) =>
      keys.some((k) => String(s?.key ?? "").toLowerCase().includes(k.toLowerCase()))
    );
    const data = section?.components?.[0]?.instance?.data;
    return data?.items?.[0] ?? data ?? null;
  };

  const bannerData = findSectionData("banner-section");
  const heroTitle = bannerData?.title ?? "";
  const heroDescription = bannerData?.description ?? "";
  const heroBg = bannerData?.bg_image?.items?.[0] ?? {};
  const heroBgMobile = heroBg?.image_mobile ?? "";
  const heroBgDesktop = heroBg?.image_desktop ?? "";
  const heroBgMobileAlt = heroBg?.mobile_image_alt_tag ?? "";
  const heroBgDesktopAlt = heroBg?.desktop_image_alt_tag ?? "";

  if (isLoading) {
    return <PageLoading />;
  }

  return (
    <div className="relative px-[20px] md:px-[40px] xl:px-[60px] xl:max-w-[1440px] 2xl:max-w-[1920px] mx-auto">
      <ContactHero
        headline={
          <h1 className="font-lexend font-extralight text-[#ffffff] max-w-[782px]">
            {(() => {
              const words = heroTitle.trim().split(/\s+/);
              return (
                <>
                  {words.slice(0, 2).join(" ")}{" "}
                  {words.length > 2 ? (
                    <span className="font-medium">{words.slice(2).join(" ")}</span>
                  ) : null}
                </>
              );
            })()}
          </h1>
        }
        description={heroDescription}
        showSearch
        backgroundImageMobile={heroBgMobile || undefined}
        backgroundImageDesktop={heroBgDesktop || undefined}
        backgroundImageMobileAlt={heroBgMobileAlt || undefined}
        backgroundImageDesktopAlt={heroBgDesktopAlt || undefined}
      />
      <BackgroundGradients count={MARKETPLACE_ZIGZAG_COUNT} />
      <ProductListing
        products={products}
        totalCount={totalCount}
        currentPage={currentPage}
        totalPages={totalPages}
        onPageChange={setCurrentPage}
        pageSize={pageSize}
        onPageSizeChange={setPageSize}
        sortOptions={sortOptions}
      />
      <Footer />
    </div>
  );
}
