import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuthToken } from "../hooks/use-root-data";
import { UserCollection, UserCollectionAddProducts } from "../../src/api/types";
import { useToast } from "../hooks/use-toast";
import { createApiApi } from "../utils/api-client-factory";

/**
 * Custom hook to fetch user's collections (sets)
 */
export const useUserCollections = () => {
  const token = useAuthToken();
  const apiApi = createApiApi(token);

  return useQuery({
    queryKey: ["userCollections"],
    queryFn: async (): Promise<UserCollection[]> => {
      if (!token) throw new Error("Authentication required");
      return await apiApi.apiCollectionV1UserCollectionsList();
    },
    enabled: !!token,
  });
};

/**
 * Custom hook to fetch a single collection by ID
 */
export const useUserCollection = (collectionId: string) => {
  const token = useAuthToken();
  const apiApi = createApiApi(token);

  return useQuery({
    queryKey: ["userCollection", collectionId],
    queryFn: async (): Promise<UserCollection> => {
      if (!token) throw new Error("Authentication required");
      return await apiApi.apiCollectionV1UserCollectionsRead({
        id: collectionId,
      });
    },
    enabled: !!token && !!collectionId,
  });
};

/**
 * Custom hook to create a new collection
 */
export const useCreateCollection = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: async (data: UserCollection): Promise<UserCollection> => {
      if (!token) throw new Error("Authentication required");
      const apiApi = createApiApi(token);
      return await apiApi.apiCollectionV1UserCollectionsCreate({ data });
    },
    onSuccess: () => {
      toast({
        title: "موفق",
        description: "ست با موفقیت ایجاد شد",
        variant: "default",
      });
      queryClient.invalidateQueries({ queryKey: ["userCollections"] });
    },
    onError: (error: Error) => {
      console.error("Collection creation failed:", error);
      toast({
        title: "خطا",
        description: "خطا در ایجاد ست. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};

/**
 * Custom hook to delete a collection
 */
export const useDeleteCollection = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: async (collectionId: string): Promise<void> => {
      if (!token) throw new Error("Authentication required");
      const apiApi = createApiApi(token);
      await apiApi.apiCollectionV1UserCollectionsDelete({ id: collectionId });
    },
    onSuccess: () => {
      toast({
        title: "موفق",
        description: "ست با موفقیت حذف شد",
        variant: "default",
      });
      queryClient.invalidateQueries({ queryKey: ["userCollections"] });
    },
    onError: (error: Error) => {
      console.error("Collection deletion failed:", error);
      toast({
        title: "خطا",
        description: "خطا در حذف ست. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};

/**
 * Custom hook to add products to a collection
 */
export const useAddProductsToCollection = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: async ({
      collectionId,
      productIds,
    }: {
      collectionId: string;
      productIds: string[];
    }): Promise<UserCollection> => {
      if (!token) throw new Error("Authentication required");
      const apiApi = createApiApi(token);
      const data: UserCollectionAddProducts = { productIds };
      return await apiApi.apiCollectionV1UserCollectionsProductsCreate({
        id: collectionId,
        data,
      });
    },
    onSuccess: (_, variables) => {
      toast({
        title: "موفق",
        description: "محصول با موفقیت به ست اضافه شد",
        variant: "default",
      });
      queryClient.invalidateQueries({ queryKey: ["userCollections"] });
      queryClient.invalidateQueries({
        queryKey: ["userCollection", variables.collectionId],
      });
    },
    onError: (error: Error) => {
      console.error("Add products to collection failed:", error);
      toast({
        title: "خطا",
        description: "خطا در اضافه کردن محصول به ست. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};

/**
 * Custom hook to remove a product from a collection
 */
export const useRemoveProductFromCollection = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: async ({
      collectionId,
      productId,
    }: {
      collectionId: string;
      productId: string;
    }): Promise<void> => {
      if (!token) throw new Error("Authentication required");
      const apiApi = createApiApi(token);
      await apiApi.apiCollectionV1UserCollectionsProductsDelete({
        id: collectionId,
        productId,
      });
    },
    onSuccess: (_, variables) => {
      toast({
        title: "موفق",
        description: "محصول از ست حذف شد",
        variant: "default",
      });
      queryClient.invalidateQueries({ queryKey: ["userCollections"] });
      queryClient.invalidateQueries({
        queryKey: ["userCollection", variables.collectionId],
      });
    },
    onError: (error: Error) => {
      console.error("Remove product from collection failed:", error);
      toast({
        title: "خطا",
        description: "خطا در حذف محصول از ست. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};

/**
 * Custom hook to update a collection (title/description)
 */
export const useUpdateCollection = () => {
  const token = useAuthToken();
  const queryClient = useQueryClient();
  const { toast } = useToast();

  return useMutation({
    mutationFn: async ({
      collectionId,
      data,
    }: {
      collectionId: string;
      data: UserCollection;
    }): Promise<UserCollection> => {
      if (!token) throw new Error("Authentication required");
      const apiApi = createApiApi(token);
      return await apiApi.apiCollectionV1UserCollectionsPartialUpdate({
        id: collectionId,
        data,
      });
    },
    onSuccess: (_, variables) => {
      toast({
        title: "موفق",
        description: "ست با موفقیت به‌روزرسانی شد",
        variant: "default",
      });
      queryClient.invalidateQueries({ queryKey: ["userCollections"] });
      queryClient.invalidateQueries({
        queryKey: ["userCollection", variables.collectionId],
      });
    },
    onError: (error: Error) => {
      console.error("Collection update failed:", error);
      toast({
        title: "خطا",
        description: "خطا در به‌روزرسانی ست. لطفاً دوباره تلاش کنید",
        variant: "destructive",
      });
    },
  });
};
