import { Button, useToast } from '@chakra-ui/react'
import { HeartIcon } from 'lucide-react'
import React from 'react'
import { useQuery } from 'react-query'
import { getAuth } from '~/libs/auth'
import clsxm from '~/libs/clsxm'
import { getUserWishlist, upsertUserWishlist } from '~/services/wishlist'

type Props = {
  productId: number
}

const AddToWishlist = ({ productId }: Props) => {
  const auth = getAuth()
  const toast = useToast({
    position: 'top',
    isClosable: true
  })

  const searchParams = { product_id: productId.toString() }
  const query = useQuery({
    queryKey: ['wishlist', searchParams, auth],
    queryFn: () => {
      if (typeof auth !== 'object') return null;
      return getUserWishlist(auth.id, searchParams)
    },
    refetchOnWindowFocus: false
  })

  const isAdded = query.data?.product_total ? query.data.product_total > 0 : false;

  const toggleWishlist = async () => {
    if (typeof auth !== 'object') return;
    await upsertUserWishlist(auth.id, productId)
    await query.refetch()
  }

  const handleClick = async () => {
    toast.promise(toggleWishlist(), {
      loading: { title: 'Update Wishlist', description: 'Mohon tunggu...' },
      success: { title: 'Update Wishlist', description: 'Berhasil update wishlist' },
      error: { title: 'Update Wishlist', description: 'Gagal update wishlist' },
    })
  }

  return (
    <Button
      variant='link'
      colorScheme='gray'
      onClick={handleClick}
      leftIcon={<HeartIcon size={18} className={clsxm('transition-colors', {
        'text-danger-500 fill-danger-500': isAdded,
        'fill-transparent': !isAdded
      })} />}
    >
      Wishlist
    </Button>
  )
}

export default AddToWishlist