import { useQuery } from "@tanstack/react-query";
import { getProduct } from "@/app/product/service/Service";
import {
  ProductDetailResponse,
  Product,
  ProductVariant,
} from "@/types/product.types";
import { LocalCartItem } from "@/app/product/store/LocalCartStore";

// Type for enriched offline cart item
export type EnrichedOfflineCartItem = LocalCartItem & {
  product: Product | null;
  variant: ProductVariant | null;
  isLoading: boolean;
};

export const useOfflineCartProducts = (localCartItems: LocalCartItem[]) => {
  // Get unique product IDs from local cart items
  const productIds = [
    ...new Set(localCartItems.map((item) => item.productId.toString())),
  ];

  // Use a single query with multiple product IDs
  const { data: productsData, isLoading, error } = useQuery<
    Map<string, ProductDetailResponse["results"]>
  >({
    queryKey: ["offline-cart-products", productIds],
    queryFn: async () => {
      if (productIds.length === 0) return new Map();

      // Fetch all products in parallel
      const productPromises = productIds.map(async (productId) => {
        try {
          const response = await getProduct(productId);
          return { productId, data: response.results };
        } catch (error) {
          console.error(`Failed to fetch product ${productId}:`, error);
          return { productId, data: null };
        }
      });

      const results = await Promise.all(productPromises);
      const productMap = new Map<string, ProductDetailResponse["results"]>();

      results.forEach(({ productId, data }) => {
        if (data) {
          productMap.set(productId, data);
        }
      });

      return productMap;
    },
    enabled: productIds.length > 0,
    staleTime: 1000 * 60 * 10, // 10 minutes
  });

  // Create enriched cart items with product data
  const enrichedCartItems = localCartItems.map((item) => {
    const productData = productsData?.get(item.productId.toString());

    if (!productData) {
      return {
        ...item,
        product: null,
        variant: null,
        isLoading: isLoading,
      };
    }

    // Find the variant that matches the variantId
    const variant = productData.product.variants?.find(
      (v) => v._id === item.variantId
    );

    return {
      ...item,
      product: productData.product,
      variant: variant || null,
      isLoading: false,
    };
  });

  return {
    enrichedCartItems,
    isLoading,
    hasError: !!error,
    productMap: productsData || new Map(),
  };
};
