"use client";
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { erc20Abi, zeroAddress, parseEther } from "viem";
import {
useAccount,
useChainId,
useSwitchChain,
useWriteContract,
useWaitForTransactionReceipt,
useSendTransaction,
} from "wagmi";
import { useAppKit } from "@reown/appkit/react";
import { Card, CardContent } from "@/components/ui/card";
import { useToast } from "@/hooks/use-toast";
import Image from "next/image";
interface Props {
currency?: `0x${string}`;
price: number;
paymentReceiverAddress: `0x${string}`;
chainId: number;
}
const CryptoProductCard = ({
currency = zeroAddress,
price,
paymentReceiverAddress,
chainId,
}: Props) => {
const [isPaymentProcessing, setPaymentProcessing] = useState<boolean>(false);
const [isMounted, setMounted] = useState<boolean>(false);
const { open } = useAppKit();
const { address, isConnected, isConnecting, isReconnecting } = useAccount();
const { switchChain } = useSwitchChain();
const currentChainId = useChainId();
const { toast } = useToast();
const activeChainId: number = chainId;
const currencySymbol: string = "USDT";
const { data: nativePaymentHash, sendTransaction } = useSendTransaction({
mutation: {
onSuccess: () => {
setPaymentProcessing(true);
},
onError: () => {
toast({
title: "Execution reverted",
description:
"Insufficient balance or transaction reverted. Please try again.",
variant: "destructive",
});
},
},
});
const { isSuccess: isNativePaymentSuccess } = useWaitForTransactionReceipt({
hash: nativePaymentHash,
});
const { data: ercPaymentHash, writeContract } = useWriteContract({
mutation: {
onSuccess: () => {
setPaymentProcessing(true);
},
onError: (error) => {
console.log(error);
toast({
title: "Execution reverted",
description:
"Insufficient balance or transaction reverted. Please try again.",
});
},
},
});
const { isSuccess: isErcPaymentSuccess } = useWaitForTransactionReceipt({
hash: ercPaymentHash,
});
const handlePayment = () => {
try {
if ((currency as `0x${string}`) === zeroAddress) {
sendTransaction({
to: paymentReceiverAddress,
value: parseEther(price.toString()),
});
} else {
writeContract({
abi: erc20Abi,
address: currency,
functionName: "transfer",
args: [paymentReceiverAddress, parseEther(price.toString())],
});
}
} catch (error) {
console.log(error);
}
};
const handleChainSwitch = () => {
if (currentChainId === activeChainId) {
return;
}
switchChain({ chainId: activeChainId });
};
useEffect(() => {
if (isErcPaymentSuccess || isNativePaymentSuccess) {
toast({
title: "Payment successful",
description:
"Your payment is complete. Thank you for shopping with us.",
});
}
setPaymentProcessing(false);
}, [isErcPaymentSuccess, isNativePaymentSuccess]);
useEffect(() => {
setMounted(true);
}, []);
return (
<div>
{isMounted && isConnected && address && (
<div className="absolute top-4 right-10">
<w3m-account-button />
</div>
)}
<Card className="w-[300px] h-[472px] shadow">
<CardContent className="p-3 relative">
<div className="text-indigo-500 border border-indigo-500 rounded-full p-1 font-bold text-xs w-[80px] absolute top-3 left-2 flex justify-center items-center">
Best seller
</div>
<div className="h-[345px]">
<Image
src="https://purepng.com/public/uploads/thumbnail//rolex-submariner-date-au9.png"
alt="Rolex Submariner Date"
width={0}
height={0}
className="w-full px-6 h-[345px]"
unoptimized
/>
</div>
<div className="mb-3 text-center flex flex-col gap-1">
<p className="">Rolex Submariner</p>
<p className="font-bold">
{price} {currencySymbol}
</p>
</div>
{isMounted ? (
<div>
{isConnecting || isReconnecting ? (
<Button
disabled
className="bg-indigo-500 w-full flex items-center gap-2 text-white font-medium rounded-[8px]"
>
<div className="w-3.5 h-3.5 border-2 border-gray-400 border-b-transparent rounded-full inline-block box-border animate-spin" />
Loading
</Button>
) : !isConnected || !address ? (
<Button onClick={() => open()} className="bg-indigo-500 w-full">
Connect
</Button>
) : !isConnecting &&
!isReconnecting &&
currentChainId !== activeChainId ? (
<Button
onClick={handleChainSwitch}
className="bg-red-500 text-white hover:text-black w-full rounded-[8px]"
>
Switch to sepolia
</Button>
) : (
<Button
disabled={isPaymentProcessing}
onClick={handlePayment}
className="bg-indigo-500 w-full disabled:opacity-80 font-medium text-white hover:text-black rounded-[8px]"
>
{isPaymentProcessing ? (
<div className="flex items-center gap-2">
<div className="w-3.5 h-3.5 border-2 border-gray-400 border-b-transparent rounded-full inline-block box-border animate-spin" />
Processing
</div>
) : (
"Buy now"
)}
</Button>
)}
</div>
) : (
<Button
disabled
className="bg-indigo-500 w-full flex items-center gap-2 text-white font-medium rounded-[8px]"
>
<div className="w-3.5 h-3.5 border-2 border-gray-400 border-b-transparent rounded-full inline-block box-border animate-spin" />
Loading
</Button>
)}
</CardContent>
</Card>
</div>
);
};
export default CryptoProductCard;