import { useAccount, useSwitchChain, useWatchAsset } from "wagmi";

import type { Token } from "@providers/ConfigProvider";

export const AddTokenToWallet = ({ token }: { token: Token }) => {
	const { connector, chainId } = useAccount();
	const { watchAsset } = useWatchAsset();
	const { switchChainAsync } = useSwitchChain();

	async function addToken() {
		try {
			if (chainId !== token.chainId) {
				await switchChainAsync({ chainId: token.chainId });
			}

			const result = await watchAsset({
				type: "ERC20",
				options: {
					address: token.address,
					symbol: token.symbol,
					decimals: token.decimals,
					image: token.logoURI,
				},
			});
		} catch (error) {
			console.log("Error", error);
		}
	}

	return (
		<button
			type="button"
			onClick={addToken}
			className="bn-flex bn-rounded-full bn-py-2 bn-px-3 bn-border bn-border-solid bn-border-primary bn-bg-layer-2 bn-items-center bn-gap-2 bn-text-primary bn-font-medium bn-w-auto bn-mx-auto bn-mt-2 bn-cursor-pointer"
		>
			{connector?.icon && (
				<img src={connector.icon} alt="wallet icon" className="bn-size-4" />
			)}
			Add {token.symbol} to {connector?.name ?? "Wallet"}
		</button>
	);
};
