import type { ButtonHTMLAttributes, ReactNode } from "react";

import type { Token } from "@/types/index";
import { useMappedChainData } from "@hooks/useMappedChainData";
import { useTheme } from "@hooks/useTheme";
import { adjustDecimals } from "@utils/adjustDecimals";
import { getBorderRadius } from "@utils/getBorderRadius";
import { twMerge } from "@utils/tailwindMerge";
import { TokenIcon } from "./TokenIcon";
import { Tooltip } from "./Tooltip";

type TokenChipProps = {
	token: Token;
	active?: boolean;
	showChain?: boolean;
	classNames?: string;
	big?: boolean;
	amount?: string;
	children?: ReactNode;
} & ButtonHTMLAttributes<HTMLButtonElement>;

export const TokenChip = ({
	token,
	onClick,
	active,
	showChain,
	classNames,
	big = false,
	amount,
	children,
	disabled = false,
	...buttonProps
}: TokenChipProps) => {
	const mappedChainData = useMappedChainData();
	const theme = useTheme();
	const styles = twMerge(
		`bn-p-2 bn-flex bn-items-center bn-cursor-pointer bn-bg-layer-2 bn-border-none bn-font-semibold bn-text-primary bn-space-x-1.5 disabled:bn-opacity-20 ${
			big ? "bn-text-lg bn-leading-[22px]" : "bn-text-sm"
		}`,
		classNames,
	);

	const tokenStyle = "bn-relative bn-size-5";

	return (
		<button
			onClick={onClick}
			className={styles}
			disabled={disabled}
			type="button"
			style={{ borderRadius: getBorderRadius(theme.borderRadius, 20) }}
			{...buttonProps}
		>
			<div className={tokenStyle}>
				<TokenIcon url={token.logoURI} classNames="bn-size-full" />
				{showChain && (
					<TokenIcon
						url={mappedChainData?.[token.chainId]?.icon ?? ""}
						classNames="bn-h-2.5 bn-w-2.5 bn-absolute bn-bottom-0 -bn-right-[2.5px]"
					/>
				)}
			</div>

			<span className="bn-whitespace-nowrap">
				{amount && (
					<Tooltip content={amount} placement="top">
						<span>{adjustDecimals({ value: amount, decimals: 3 })}</span>
					</Tooltip>
				)}{" "}
				{token.symbol}
			</span>
			{children}
		</button>
	);
};
