import {
  useMutation,
  useInfiniteQuery,
  useQuery,
  useQueryClient,
} from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import {
  InstagramSyncRequest,
  ApiInstageramV1InstagramSyncCreate201Response,
} from "../../src/api/types";
import { toast } from "~/hooks/use-toast";
import { createInstagramManagementApi, createApiApi } from "~/utils/api-client-factory";

/**
 * Custom hook to fetch Instagram posts with infinite scroll
 */
export const useGetInstagramPosts = () => {
  const token = useAuthToken();

  return useInfiniteQuery({
    queryKey: ["instagram-posts"],
    queryFn: async ({ pageParam }: { pageParam: string | undefined }) => {
      if (!token) throw new Error("Authentication required");

      const instagramApi = createInstagramManagementApi(token);
      const posts = await instagramApi.apiInstageramV1InstagramPostsList({
        cursor: pageParam,
      });

      return posts;
    },
    getNextPageParam: (lastPage) => {
      if (!lastPage.next) return undefined;
      // Extract cursor from the next URL
      const url = new URL(lastPage.next);
      const cursor = url.searchParams.get("cursor");
      return cursor || undefined;
    },
    initialPageParam: undefined as string | undefined,
    enabled: !!token,
  });
};

/**
 * Custom hook to fetch Instagram post details by ID
 */
export const useGetInstagramPostDetails = (
  id: string,
  options?: { enabled?: boolean }
) => {
  const token = useAuthToken();

  return useQuery({
    queryKey: ["instagram-post-details", id],
    queryFn: async () => {
      if (!token) throw new Error("Authentication required");

      const instagramApi = createInstagramManagementApi(token);
      return await instagramApi.apiInstageramV1InstagramPostsRead({ id });
    },
    enabled: !!token && !!id && (options?.enabled ?? true),
    staleTime: 10 * 60 * 1000, // 10 minutes
    gcTime: 15 * 60 * 1000, // 15 minutes (formerly cacheTime)
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: false,
  });
};

/**
 * Custom hook to sync Instagram posts
 */
export const useInstagramSync = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (
      data: InstagramSyncRequest
    ): Promise<ApiInstageramV1InstagramSyncCreate201Response> => {
      if (!token) throw new Error("Authentication required");

      const instagramApi = createInstagramManagementApi(token);
      return await instagramApi.apiInstageramV1InstagramSyncCreate({ data });
    },
    onSuccess: (data) => {
      console.log("your posts sync successfully", data);
      toast({
        title: "پست ها با موفقیت دریافت شدند",
        description: `پست های آخر پیج شما دریافت شد و شما امروز ${data.remainingToday} پست دیگر میتوانید دریافت کنید`,
      });
      queryClient.invalidateQueries({ queryKey: ["instagram-posts"] });
    },
    onError: () => {
      console.log("error in sync your posts");
      toast({
        title: "خطا در دریافت پست ها",
        description:
          "ممکن است پیج شما private باشد یا مجوز دسترسی به آن را نداشته باشید یا در حال حاظر سرور پایین باشا. در غیر اینصورت با پشتیبانی ارتباط برقرار کنید",
        variant: "destructive",
      });
    },
    gcTime: 60000,
    retry: 3,
    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
  });
};

/**
 * Custom hook to generate product from Instagram post
 */
export const useGenerateProductFromPost = (
  id: string,
  options?: { enabled?: boolean }
) => {
  const token = useAuthToken();

  return useQuery({
    queryKey: ["generate-product-from-post", id],
    queryFn: async () => {
      if (!token) throw new Error("Authentication required");

      const apiApi = createApiApi(token);
      return await apiApi.apiApgsV1PostsGenerateProductCreate({
        id: id,
      });
    },
    enabled: !!token && !!id && (options?.enabled ?? true),
    staleTime: 10 * 60 * 1000, // 10 minutes
    gcTime: 15 * 60 * 1000, // 15 minutes
    refetchOnWindowFocus: false,
    refetchOnMount: false,
    refetchOnReconnect: false,
  });
};

/**
 * Custom hook to delete Instagram post
 */
export const useDeleteInstagramPost = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (id: string) => {
      if (!token) throw new Error("Authentication required");

      const instagramApi = createInstagramManagementApi(token);
      return await instagramApi.apiInstageramV1InstagramPostsDelete({ id });
    },
    onSuccess: () => {
      toast({
        title: "پست با موفقیت حذف شد",
        description: "پست انتخاب شده از لیست پست‌های شما حذف گردید",
      });
      // Invalidate Instagram posts queries to refresh the list
      queryClient.invalidateQueries({ queryKey: ["instagram-posts"] });
    },
    onError: () => {
      toast({
        title: "خطا در حذف پست",
        description:
          "متأسفانه نتوانستیم پست را حذف کنیم. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};
