"use client";

import ProductsPageTop from "./ProductPageTop";
import MainProductView from "./MainProductView";
import SingleProductView from "./SingleProductView";
import ScrollBottom from "@/components/Home/subComponents/ScrollBottom";
import {
  useCategories,
  useProductCollections,
  useProducts,
} from "@/hooks/useData";

// ✅ Filter active categories recursively
const filterActiveCategories = (categories) => {
  return categories
    .filter((cat) => cat.category_status === 1)
    .map((cat) => ({
      ...cat,
      children: filterActiveCategories(cat.children || []),
    }));
};

// ✅ Get all valid category IDs
const getValidCategoryIds = (categories) => {
  const ids = new Set();
  const collect = (cats) => {
    for (const cat of cats || []) {
      if (cat.category_status === 1) {
        ids.add(cat.id);
        if (cat.children?.length) collect(cat.children);
      }
    }
  };
  collect(categories);
  return ids;
};

// ✅ UTIL: Find category by slug
const findCategoryBySlug = (categoriesRaw, slugPath) => {
  const categories = Array.isArray(categoriesRaw)
    ? categoriesRaw
    : categoriesRaw?.rows || [];
  let matched = null;

  const traverse = (nodes = []) => {
    for (const node of nodes) {
      if (node?.category_url === slugPath) {
        matched = node;
        return;
      }
      if (Array.isArray(node.children)) traverse(node.children);
    }
  };

  traverse(categories);
  return matched;
};

// ✅ UTIL: Get all child category IDs
const collectAllChildCategoryIds = (category) => {
  const ids = [category.id];
  const collect = (children) => {
    for (const child of children || []) {
      ids.push(child.id);
      if (child.children?.length) collect(child.children);
    }
  };
  collect(category.children);
  return ids;
};

// ✅ NEW: Attach product count to parent + children
const attachProductCountsWithRollup = (categories, products) => {
  const countMap = new Map();
  products.forEach((p) => {
    countMap.set(p.category_id, (countMap.get(p.category_id) || 0) + 1);
  });

  const attach = (nodes) =>
    nodes.map((node) => {
      const children = node.children?.length ? attach(node.children) : [];
      const selfCount = countMap.get(node.id) || 0;
      const childCount = children.reduce(
        (acc, cur) => acc + (cur.count || 0),
        0
      );
      return {
        ...node,
        count: selfCount + childCount,
        children,
      };
    });

  return attach(categories);
};

const DynamicPage = ({ slug }) => {
  const { data: allCategories } = useCategories();

  const { data: allProducts } = useProducts();

  const { data: collections } = useProductCollections();

  if (!allCategories || !allProducts || !collections) return null;

  const rawCategoryList = Array.isArray(allCategories)
    ? allCategories
    : allCategories.rows || [];

  const allCategoryList = filterActiveCategories(rawCategoryList);
  const validCategoryIdSet = getValidCategoryIds(allCategoryList);
  const allProductList = (allProducts.rows || []).filter((p) =>
    validCategoryIdSet.has(p.category_id)
  );

  const allCollectionList = collections.rows || [];
  const slugPath = slug.join("/");

  // ✅ 4. Product match (by slug)
  const matchedProduct = allProductList.find((p) => p.product_url === slugPath);

  if (matchedProduct) {
    const relatedProducts = allProductList.filter(
      (p) =>
        p.category_id === matchedProduct.category_id &&
        p.id !== matchedProduct.id &&
        p.status === 1
    );
    return (
      <>
        <SingleProductView product={matchedProduct} />
        {relatedProducts.length > 0 && (
          <div className="mt-16">
            <ScrollBottom
              data={{
                name: "Related Products",
                items: relatedProducts,
              }}
            />
          </div>
        )}
      </>
    );
  }

  // ✅ 5. Category view
  const matchedCategory = findCategoryBySlug(allCategoryList, slugPath);

  if (matchedCategory) {
    const validCategoryIds = collectAllChildCategoryIds(matchedCategory);
    const filteredProducts = allProductList.filter((product) =>
      validCategoryIds.includes(product.category_id)
    );

    const categoryWithCounts = attachProductCountsWithRollup(
      matchedCategory.children || [],
      allProductList
    );

    return (
      <>
        <ProductsPageTop
          name={matchedCategory.name}
          categories={matchedCategory.children}
        />
        <MainProductView
          categories={categoryWithCounts}
          products={filteredProducts}
          categoryTree={categoryWithCounts}
        />
      </>
    );
  }

  // ✅ 6. Collection view
  const matchedCollection = allCollectionList.find(
    (col) => col.url === slugPath
  );

  if (matchedCollection) {
    const refIds = matchedCollection.refids.map((id) => Number(id));
    const isCategoryRef = matchedCollection.ref_table === "categories";

    const filteredProducts = isCategoryRef
      ? allProductList.filter((p) => refIds.includes(p.category_id))
      : allProductList.filter((p) => refIds.includes(p.id));

    let derivedCategories = [];

    if (!isCategoryRef && filteredProducts.length && allCategoryList?.length) {
      const categoryMap = new Map();

      const traverse = (nodes) => {
        for (const node of nodes || []) {
          if (node?.id) categoryMap.set(node.id, node);
          if (node.children?.length) traverse(node.children);
        }
      };

      traverse(allCategoryList);

      const uniqueCatIds = new Set(filteredProducts.map((p) => p.category_id));

      derivedCategories = Array.from(uniqueCatIds)
        .map((id) => categoryMap.get(id))
        .filter(Boolean)
        .map((cat) => ({
          ...cat,
          count: filteredProducts.filter((p) => p.category_id === cat.id)
            .length,
        }));
    }

    return (
      <>
        <ProductsPageTop
          name={matchedCollection.name}
          backgroundImage={matchedCollection.image}
        />
        <MainProductView
          categories={derivedCategories}
          products={filteredProducts}
          categoryTree={attachProductCountsWithRollup(
            allCategoryList,
            filteredProducts
          )}
          collection={matchedCollection} // ✅ Pass collection
        />
      </>
    );
  }

  return <div className="text-center py-10 text-gray-500">Page not found</div>;
};

export default DynamicPage;
