|
| 1 | +import React, { useEffect, useState } from "react"; |
| 2 | +import { |
| 3 | + Menu, |
| 4 | + MenuButton, |
| 5 | + MenuList, |
| 6 | + MenuItem, |
| 7 | + Button, |
| 8 | + HStack, |
| 9 | + Text, |
| 10 | +} from "@chakra-ui/react"; |
| 11 | +import { useRouter } from "next/router"; |
| 12 | +import { useQuery } from "react-query"; |
| 13 | +import axios from "axios"; |
| 14 | +import { BsChevronDown } from "react-icons/bs"; |
| 15 | +import { IoIosFlash } from "react-icons/io"; |
| 16 | + |
| 17 | +const BuyShotButton = ({ |
| 18 | + credits, |
| 19 | + onPaymentSuccess, |
| 20 | +}: { |
| 21 | + credits: number; |
| 22 | + onPaymentSuccess: (credits: number) => void; |
| 23 | +}) => { |
| 24 | + const { push, query } = useRouter(); |
| 25 | + const [waitingPayment, setWaitingPayment] = useState(false); |
| 26 | + |
| 27 | + const { isLoading } = useQuery( |
| 28 | + "check-shot-payment", |
| 29 | + () => |
| 30 | + axios.get(`/api/checkout/check/${query.ppi}/${query.session_id}/shot`), |
| 31 | + { |
| 32 | + cacheTime: 0, |
| 33 | + refetchInterval: 4, |
| 34 | + retry: 0, |
| 35 | + enabled: waitingPayment, |
| 36 | + onSuccess: (response) => { |
| 37 | + onPaymentSuccess(response.data.credits); |
| 38 | + }, |
| 39 | + onSettled: () => { |
| 40 | + setWaitingPayment(false); |
| 41 | + }, |
| 42 | + } |
| 43 | + ); |
| 44 | + |
| 45 | + useEffect(() => { |
| 46 | + setWaitingPayment(query.ppi === query.id); |
| 47 | + }, [query]); |
| 48 | + |
| 49 | + const handleShotPayment = (quantity: number) => { |
| 50 | + push(`/api/checkout/shots?quantity=${quantity}&ppi=${query.id}`); |
| 51 | + }; |
| 52 | + |
| 53 | + return ( |
| 54 | + <Menu> |
| 55 | + <MenuButton |
| 56 | + rightIcon={<BsChevronDown />} |
| 57 | + isLoading={isLoading} |
| 58 | + size="xs" |
| 59 | + shadow="none" |
| 60 | + variant="brand" |
| 61 | + as={Button} |
| 62 | + > |
| 63 | + <HStack spacing={0}> |
| 64 | + <IoIosFlash /> |
| 65 | + {credits === 0 ? ( |
| 66 | + <Text>Buy more shots</Text> |
| 67 | + ) : ( |
| 68 | + <Text> |
| 69 | + {credits} Shot{credits > 1 && "s"} left |
| 70 | + </Text> |
| 71 | + )} |
| 72 | + </HStack> |
| 73 | + </MenuButton> |
| 74 | + <MenuList fontSize="sm"> |
| 75 | + <MenuItem |
| 76 | + command="$4" |
| 77 | + onClick={() => { |
| 78 | + handleShotPayment(100); |
| 79 | + }} |
| 80 | + > |
| 81 | + Add <b>100 shots</b> |
| 82 | + </MenuItem> |
| 83 | + <MenuItem |
| 84 | + command="$7" |
| 85 | + onClick={() => { |
| 86 | + handleShotPayment(200); |
| 87 | + }} |
| 88 | + > |
| 89 | + Add <b>200 shots</b> |
| 90 | + </MenuItem> |
| 91 | + <MenuItem |
| 92 | + command="$9" |
| 93 | + onClick={() => { |
| 94 | + handleShotPayment(300); |
| 95 | + }} |
| 96 | + > |
| 97 | + Add <b>300 shots</b> |
| 98 | + </MenuItem> |
| 99 | + </MenuList> |
| 100 | + </Menu> |
| 101 | + ); |
| 102 | +}; |
| 103 | + |
| 104 | +export default BuyShotButton; |
0 commit comments