"use client";

import React, { useMemo } from "react";

import ThreeBoxSection from "./subComponents/3-box-section";
import ScrollTop from "./subComponents/ScrollTop";
import ScrollBottom from "./subComponents/ScrollBottom";
import ComboBox from "./subComponents/ComboBox";

import {
  useAssignCollections,
  useCategoriesAll,
  useProductCollections,
  useProducts,
} from "@/hooks/useData";

const Collections = ({ section_type }) => {
  const { data: assignCollections } = useAssignCollections();

  const { data: collections } = useProductCollections();

  const { data: allProducts } = useProducts();

  const { data: allCategories } = useCategoriesAll();

  const filteredSections =
    assignCollections?.rows?.filter(
      (item) => item.section_type === section_type
    ) || [];

  const resolvedSections = useMemo(() => {
    if (
      !assignCollections?.rows ||
      !collections?.rows ||
      !allProducts?.rows ||
      !allCategories?.rows
    ) {
      return [];
    }

    return filteredSections.map((section) => {
      const collectionItems = (section.collection_ids || []).map((id) => {
        const collection = collections.rows.find(
          (col) => col.id === id && col.status === 1
        );
        if (!collection) return null;

        const refIds = collection.refids || [];
        let items = [];

        if (collection.ref_table === "products") {
          items = allProducts.rows.filter((prod) => refIds.includes(prod.id));
        } else if (collection.ref_table === "categories") {
          items = allCategories.rows.filter((cat) => refIds.includes(cat.id));
        }

        if (!items || items.length === 0) {
          console.warn("⚠️ No matching items for collection:", {
            collection: collection.name,
            ref_table: collection.ref_table,
            refIds,
          });
        }

        return { ...collection, items: items || [] };
      });

      return {
        ...section,
        collections: collectionItems.filter(Boolean),
      };
    });
  }, [
    assignCollections,
    collections,
    allProducts,
    allCategories,
    section_type,
  ]);

  // Now safe to return conditionally
  if (!assignCollections || !collections || !allProducts || !allCategories)
    return null;

  return (
    <>
      {(resolvedSections || []).map((section, idx) => {
        switch (section.section_type) {
          case "3-box-section":
            return <ThreeBoxSection key={idx} data={section.collections} />;
          case "combo-box":
            return <ComboBox key={idx} data={section.collections} />;
          case "scroll-top":
          case "scroll-bottom":
            return (section.collections || []).map((collection, cIdx) => {
              if (collection.ref_table === "categories") {
                return <ScrollTop key={`${idx}-${cIdx}`} data={collection} />;
              }
              if (collection.ref_table === "products") {
                return (
                  <ScrollBottom key={`${idx}-${cIdx}`} data={collection} />
                );
              }
              return null;
            });
          default:
            return null;
        }
      })}
    </>
  );
};

export default Collections;
