import { toast } from 'react-hot-toast'
import useWishlist from '@/lib/wishlist/hooks/useWishlist'
import createOrDeleteWishlistApi from '@/lib/wishlist/api/createOrDeleteWishlistApi'
import ProductDesktop from './ProductDesktop'
import useAuth from '@/core/hooks/useAuth'
import ProductMobile from './ProductMobile'
import { useRouter } from 'next/router'

const Product = ({ product }) => {
  const auth = useAuth()
  const router = useRouter()
  const { wishlist } = useWishlist({ productId: product?.id })

  const toggleWishlist = async () => {
    if (!auth) {
      router.push('/login')
      return
    }
    const data = { product_id: product.id }
    await createOrDeleteWishlistApi({ data })
    if (wishlist?.data?.productTotal > 0) {
      toast.success('Berhasil menghapus dari wishlist')
    } else {
      toast.success('Berhasil menambahkan ke wishlist')
    }
    wishlist.refetch()
  }

  return (
    <>
      <ProductMobile product={product} wishlist={wishlist} toggleWishlist={toggleWishlist} />
      <ProductDesktop product={product} wishlist={wishlist} toggleWishlist={toggleWishlist} />
    </>
  )
}

export default Product
