"use client";
import ThemeOptionContext from "@/context/themeOptionsContext";
import Loader from "@/layout/loader";
import Breadcrumb from "@/utils/commonComponents/breadcrumb";
import { ModifyString } from "@/utils/customFunctions/ModifyString";
import { useCustomSearchParams } from "@/utils/hooks/useCustomSearchParams";
import { useQuery, useInfiniteQuery } from "@tanstack/react-query";
import { getBusinessInfo } from "@/data/PublicApiData/business";
// import { getProduct } from "@/data/PublicApiData/business"; // unused - products fetched directly
import { useContext, useEffect, useState } from "react";
import SellerDetailClassic from "./SellerDetailClassic";
const imgURL = process.env.NEXT_PUBLIC_BACKEND_URL;


const SingleStoreDetail = ({ params }) => {
  // params is the businessId (slug would be the ID)
  const { data: storeResponse, isLoading: storeLoading } = useQuery({
    queryKey: ["sellerBusinessInfo", params],
    queryFn: () => getBusinessInfo(params),
    refetchOnWindowFocus: false,
    enabled: !!params,
  });

  // fetch products by business with pagination, loading more on scroll
  const {
    data: productsResponse,
    isLoading: productsLoading,
    fetchNextPage,
    hasNextPage,
    isFetchingNextPage,
  } = useInfiniteQuery({
    queryKey: ["sellerProducts", params],
    queryFn: async ({ pageParam = 1 }) => {
      // fetch full payload so pagination metadata is available
      console.log("queryFn pageParam", pageParam);
      const axios = (await import("axios")).default;
      const apiURL = process.env.NEXT_PUBLIC_BACKEND_API_URL;
      const { data } = await axios.get(`${apiURL}/OnlineStoreProduct/products-by-business`, {
        params: {
          BusinessId: params,
          PageIndex: pageParam,
          PageSize: 16,
        },
        paramsSerializer: {
          indexes: true,
        },
      });
      // server wraps products under a `data` key; return that if present so
      // callers can access `products` directly and pagination helpers work
      return data?.data || data;
    },
    // getNextPageParam: (lastPage) => {
    //   console.log("lastPage:", lastPage);
    //   // the server response should include a products object with pagination info
    //   const current = lastPage?.products?.PageIndex ?? lastPage?.products?.current_page;
    //   const total = lastPage?.products?.total_pages;
    //   // if either value is missing we can't calculate the next page
    //   if (current == null || total == null) return undefined;
    //   return current < total ? current + 1 : undefined;
    // },
    getNextPageParam: (lastPage, allPages) => {
      const totalPages = Number(lastPage?.products?.total_pages);
      if (!totalPages) return undefined;
      const nextPage = allPages.length + 1;
      console.log("NextPage Check:", {
        loadedPages: allPages.length,
        totalPages,
        nextPage,
      });

      return nextPage <= totalPages ? nextPage : undefined;
    },
    enabled: !!params,
    refetchOnWindowFocus: false,
  });

  useEffect(() => {
    const onScroll = () => {
      const scrollTop = window.scrollY + window.innerHeight;
      const height = document.documentElement.scrollHeight;

      if (scrollTop >= height - 200 && hasNextPage && !isFetchingNextPage) {
        fetchNextPage();
      }
    };

    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);

  // Extract actual data from response
  const StoreDataRaw = storeResponse?.data || storeResponse;

  // Normalize store data to match components' expected shape
  const StoreData = {
    ...StoreDataRaw,
    store_name: StoreDataRaw?.businessName || StoreDataRaw?.store_name,
    description: StoreDataRaw?.description || StoreDataRaw?.businessDescription || "",
    businessAddress: StoreDataRaw?.businessAddress || StoreDataRaw?.businessAddress || StoreDataRaw?.businessAddress,
    store_logo: StoreDataRaw?.store_logo || (StoreDataRaw?.image ? { original_url: `${process.env.NEXT_PUBLIC_BACKEND_URL}/uploads/${StoreDataRaw.image}.jpg` } : null),
    store_cover: StoreDataRaw?.store_cover || null,
    vendor: {
      phone: (StoreDataRaw?.businessPhone || "")?.toString().split(".")[0] || "",
      email: StoreDataRaw?.email || "",
      country_code: StoreDataRaw?.country_code || "",
    },
  };

  // Normalize seller products response into an object with `records` array
  // flatten pages if infinite
  const sellerProductsRaw =
    productsResponse?.pages
      ? productsResponse.pages.flatMap((p) => p?.products?.records || [])
      : productsResponse?.data || productsResponse;

  // helper to transform a raw record into UI-friendly product
  const normalizeRecord = (r) => ({
    id: r.id,
    name: r.name,
    slug: r.slug || r.id,
    businessId: r.businessId,
    businessName: r.businessName,
    unit: r.unit,
    unitShortName: r.unitShortName,
    product_thumbnail: { original_url: r.image ? `${imgURL}/uploads/${r.image}.jpg` : null },
    image: r.image ? `${imgURL}/uploads/${r.image}.jpg` : null,
    price: r.price || r.mrpPrice || r.salePrice || 0,
    mrpPrice: r.mrpPrice || r.price || 0,
    sale_price: r.mrpPrice || 0,
    min_sale_price: r.salePrice || r.sale_price || r.mrpPrice || 0,
    quantity: r.currentStock || r.quantity || 0,
    currentStock: r.currentStock,
    stock_status: (r.currentStock || r.quantity) > 0 ? "in_stock" : "out_of_stock",
    is_sale_enable: r.is_sale_enable || false,
    is_featured: r.is_featured || false,
    is_trending: r.is_trending || false,
    reviews_count: r.reviews_count || 0,
    rating_count: r.rating_count || 0,
    raw: r,
  });

  const mapArray = (arr) => arr.map(normalizeRecord);
  let sellerProductsForComponent;

  if (Array.isArray(sellerProductsRaw)) {
    // pages flattened or plain array
    sellerProductsForComponent = { records: mapArray(sellerProductsRaw) };
  } else if (sellerProductsRaw?.products?.records) {
    sellerProductsForComponent = {
      records: mapArray(sellerProductsRaw.products.records),
      total_records: sellerProductsRaw.products.total_records ?? sellerProductsRaw.products.total_records,
      total_pages: sellerProductsRaw.products.total_pages ?? sellerProductsRaw.products.total_pages,
    };
  } else if (sellerProductsRaw?.records) {
    sellerProductsForComponent = { ...sellerProductsRaw, records: mapArray(sellerProductsRaw.records) };
  } else if (sellerProductsRaw?.data && Array.isArray(sellerProductsRaw.data)) {
    sellerProductsForComponent = { records: mapArray(sellerProductsRaw.data) };
  } else {
    sellerProductsForComponent = { records: [] };
  }

  const [filter, setFilter] = useState({ category: [], price: [], attribute: [], rating: [], sortBy: "", field: "" });

  // Debug logging
  // useEffect(() => {
  //   console.log("Store Response:", storeResponse);
  //   console.log("Products Response (raw):", productsResponse);
  //   console.log("Normalized sellerProductsForComponent:", sellerProductsForComponent);
  // }, [storeResponse, productsResponse]);
  const { themeOption } = useContext(ThemeOptionContext);
  const [category, brand, attribute, price, rating, sortBy, field, layout] = useCustomSearchParams(["category", "brand", "attribute", "price", "rating", "sortBy", "field", "layout"]);
  const sellerDetailLayout = layout?.layout ? layout?.layout : themeOption?.collection?.collection_layout;

  useEffect(() => {
    setFilter((prev) => {
      return {
        ...prev,
        category: category ? category?.category?.split(",") : [],
        brand: brand ? brand?.brand?.split(",") : [],
        attribute: attribute ? attribute?.attribute?.split(",") : [],
        price: price ? price?.price?.split(",") : [],
        rating: rating ? rating?.rating?.split(",") : [],
        sortBy: sortBy ? sortBy?.sortBy : "",
        field: field ? field?.field : "",
      };
    });
  }, [category, brand, attribute, price, rating, sortBy, field]);
  const storeName = StoreData?.businessName || ModifyString(params, false, "-");
  if (storeLoading || productsLoading) return <Loader />;
  return (
    <>
      <Breadcrumb title={storeName} subNavigation={[{ name: "SellerStores" }, { name: storeName }]} />
      <SellerDetailClassic filter={filter} setFilter={setFilter} StoreData={StoreData} businessId={params} sellerProducts={sellerProductsForComponent} />
    </>
  );
};
export default SingleStoreDetail;
