import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
import { useCallback } from "react";
import { CollectionCursorPage } from "../../src/api/types/models";
import {
  createCollectionsPublicApi,
  createCollectionsApi,
} from "../utils/api-client-factory";

/**
 * Custom hook for infinite collections loading using cursor-based pagination
 */
export const useCollectionsInfiniteQuery = (params?: {
  q?: string;
  sellerId?: string;
  category?: string;
  trending?: number;
  pageSize?: number;
}) => {
  const collectionsApi = createCollectionsPublicApi();

  // Function to get next page URL from previous result
  const getNextPageParam = useCallback((lastPage: CollectionCursorPage) => {
    return lastPage.next || undefined;
  }, []);

  return useInfiniteQuery({
    queryKey: ["collections", params],
    queryFn: async ({ pageParam }) => {
      // If pageParam is a full URL, extract the cursor
      let cursor: string | undefined = undefined;
      if (typeof pageParam === "string" && pageParam.includes("cursor=")) {
        const url = new URL(pageParam);
        const cursorParam = url.searchParams.get("cursor");
        if (cursorParam) cursor = cursorParam;
      } else if (typeof pageParam === "string") {
        cursor = pageParam;
      }

      // Call the API with the cursor if available
      return await collectionsApi.apiCollectionV1CollectionsList({
        cursor: cursor,
        q: params?.q,
        sellerId: params?.sellerId,
        category: params?.category,
        trending: params?.trending,
        pageSize: params?.pageSize || 20,
      });
    },
    getNextPageParam,
    initialPageParam: undefined,
  });
};

/**
 * Custom hook for getting collection detail with products
 */
export const useCollectionDetail = (collectionId: string) => {
  const collectionsApi = createCollectionsPublicApi();

  return useQuery({
    queryKey: ["collection", collectionId],
    queryFn: async () => {
      return await collectionsApi.apiCollectionV1CollectionsRead({
        id: collectionId,
        pageSize: 50, // Get first 50 products
      });
    },
    enabled: !!collectionId,
  });
};

/**
 * Custom hook for getting similar collections (cursor-based pagination)
 */
export const useSimilarCollections = (collectionId: string) => {
  const collectionsApi = createCollectionsApi();

  return useQuery({
    queryKey: ["similarCollections", collectionId],
    queryFn: async () => {
      return await collectionsApi.apiCollectionV1CollectionsSimilarList({
        collectionId: collectionId,
        pageSize: 10,
      });
    },
    enabled: !!collectionId,
  });
};
