import { useAccount, useWatchAsset } from "wagmi";

import type { Token } from "@/types/index";
import { MIcon } from "@components/common/MIcon";
import { Tooltip } from "@components/common/Tooltip";
import { useChainSwitcher } from "@hooks/useChainSwitcher";
import { USER_OPERATIONS, useLogError } from "@hooks/useLogError";
import { useToast } from "@providers/ToastProvider";

export const AddTokenToWalletSmall = ({ token }: { token: Token }) => {
	const { connector, chainId } = useAccount();
	const { watchAsset } = useWatchAsset();
	const { showToast } = useToast();
	const { logError } = useLogError();
	const { switchToChain } = useChainSwitcher();

	async function addToken() {
		try {
			const chainSwitched = await switchToChain(token.chainId, chainId);
			if (!chainSwitched) return;

			await watchAsset({
				type: "ERC20",
				options: {
					address: token.address,
					symbol: token.symbol,
					decimals: token.decimals,
					image: token.logoURI,
				},
			});
		} catch (error) {
			console.log("Error", error);
			showToast("Failed to add token", "Please try again", "error");
			logError(error, {
				operation: USER_OPERATIONS.ADD_TOKEN,
			});
		}
	}

	const style =
		"bn-flex bn-items-center bn-justify-center bn-rounded-full bn-bg-layer-3 bn-mx-auto bn-cursor-pointer bn-size-9 bn-border-0";

	// biome-ignore format:
	const tooltipContent = `Add ${token.symbol} to ${connector?.name ?? "Wallet"}`

	return (
		<button type="button" onClick={addToken} className={style}>
			<Tooltip content={tooltipContent}>
				{connector?.icon ? (
					<img src={connector.icon} alt="wallet icon" className="bn-size-5" />
				) : (
					<span>
						<MIcon name="wallet" classNames="bn-text-xl bn-text-primary" />
					</span>
				)}
			</Tooltip>
		</button>
	);
};
