import { Button, useToast } from '@chakra-ui/react'
import { useRouter } from 'next/router'

import { getAuth } from '~/libs/auth'
import { upsertUserCart } from '~/services/cart'

type Props = {
  variantId: number | null,
  quantity?: number;
  source?: 'buy' | 'add_to_cart';
}

const AddToCart = ({
  variantId,
  quantity = 1,
  source = 'add_to_cart'
}: Props) => {
  const auth = getAuth()
  const router = useRouter()
  const toast = useToast({
    position: 'top',
    isClosable: true
  })

  const handleClick = async () => {
    if (typeof auth !== 'object') {
      const currentUrl = encodeURIComponent(router.asPath)
      router.push(`/login?next=${currentUrl}`)
      return;
    }

    if (
      !variantId ||
      isNaN(quantity) ||
      typeof auth !== 'object'
    ) return;

    toast.promise(
      upsertUserCart({
        userId: auth.id,
        type: 'product',
        id: variantId,
        qty: quantity,
        selected: true,
        source: source,
        qtyAppend: true
      }),
      {
        loading: { title: 'Menambahkan ke keranjang', description: 'Mohon tunggu...' },
        success: { title: 'Menambahkan ke keranjang', description: 'Berhasil menambahkan ke keranjang belanja' },
        error: { title: 'Menambahkan ke keranjang', description: 'Gagal menambahkan ke keranjang belanja' },
      }
    )

    if (source === 'buy') {
      router.push('/shop/checkout?source=buy')
    }
  }

  const btnConfig = {
    'add_to_cart': {
      colorScheme: 'yellow',
      text: 'Keranjang'
    },
    'buy': {
      colorScheme: 'red',
      text: 'Beli'
    }
  }

  return (
    <Button onClick={handleClick} colorScheme={btnConfig[source].colorScheme} className='w-full'>
      {btnConfig[source].text}
    </Button>
  )
}

export default AddToCart