import React from 'react';
import {Button} from 'theme-ui';
import {useAddDiscountToCart, useCartCount} from 'gatsby-theme-shopify-manager';
import {useProducts} from '../../utils';

export function ExampleUseAddDiscountToCart() {
  const cartCount = useCartCount();
  const addDiscountToCart = useAddDiscountToCart();
  const products = useProducts();

  async function addDiscount() {
    const discountCode = "DISCOUNT25";

    try {
      await addDiscountToCart(discountCode);
      alert('Successfully applied that discount to your cart!');
    } catch {
      alert('There was a problem applying that discount to your cart.');
    }
  }

  return (
    <>
      <p>There are currently {cartCount} items in your cart.</p>
      <Button onClick={addDiscount} sx={{mb: 3}}>
        Add a discount to your cart
      </Button>
    </>
  );
}
