import React, { FC, useState } from 'react' import cn from 'classnames' import { Heart } from '@components/icons' import { useUI } from '@components/ui' import type { Product, ProductVariant } from '@commerce/types' import useCustomer from '@framework/customer/use-customer' import useAddItem from '@framework/wishlist/use-add-item' import useRemoveItem from '@framework/wishlist/use-remove-item' import useWishlist from '@framework/wishlist/use-add-item' type Props = { productId: Product['id'] variant: ProductVariant } & React.ButtonHTMLAttributes const WishlistButton: FC = ({ productId, variant, className, ...props }) => { const { data } = useWishlist() const addItem = useAddItem() const removeItem = useRemoveItem() const { data: customer } = useCustomer() const { openModal, setModalView } = useUI() const [loading, setLoading] = useState(false) const itemInWishlist = data?.items?.find( (item) => item.product_id === productId && item.variant_id === variant.id ) const handleWishlistChange = async (e: any) => { e.preventDefault() if (loading) return // A login is required before adding an item to the wishlist if (!customer) { setModalView('LOGIN_VIEW') return openModal() } setLoading(true) try { if (itemInWishlist) { await removeItem({ id: itemInWishlist.id! }) } else { await addItem({ productId, variantId: variant?.id!, }) } setLoading(false) } catch (err) { setLoading(false) } } return ( ) } export default WishlistButton