"use client";

import { useMutation } from "convex/react";
import { useState, useCallback } from "react";
import { api } from "../../../../../convex/_generated/api";
import type { Id } from "../../../../../convex/_generated/dataModel";
import { useCartSessionId } from "@/lib/cart/useCartSessionId";

export function useWishlistMutations(): {
  removeItem: (wishlistItemId: string) => Promise<void>;
  isRemoving: boolean;
  addToCart: (variantId: string, quantity: number) => Promise<void>;
  isAddingToCart: boolean;
} {
  const [isRemoving, setIsRemoving] = useState(false);
  const [isAddingToCart, setIsAddingToCart] = useState(false);
  const sessionId = useCartSessionId();

  const removeMutation = useMutation(api.wishlists.remove);
  const addItemMutation = useMutation(api.carts.addItem);

  const removeItem = useCallback(
    async (wishlistItemId: string) => {
      setIsRemoving(true);
      try {
        await removeMutation({ id: wishlistItemId as Id<"wishlists"> });
      } finally {
        setIsRemoving(false);
      }
    },
    [removeMutation],
  );

  const addToCart = useCallback(
    async (variantId: string, quantity: number) => {
      setIsAddingToCart(true);
      try {
        await addItemMutation({
          variantId: variantId as Id<"productVariants">,
          quantity,
          sessionId: sessionId ?? undefined,
        });
      } finally {
        setIsAddingToCart(false);
      }
    },
    [addItemMutation, sessionId],
  );

  return { removeItem, isRemoving, addToCart, isAddingToCart };
}
