import { useSelector } from "react-redux";

import { Tooltip } from "@components/common/Tooltip";
import { useTokenBalance } from "@hooks/useTokenBalance";
import type { Token } from "@providers/ConfigProvider";
import type { ReduxStateType } from "@store/types";
import { abbreviateNumber } from "@utils/abbreviateNumber";
import { adjustDecimals } from "@utils/adjustDecimals";
import { formatValue } from "@utils/formatValue";

export const TokenBalance = ({ token }: { token: Token }) => {
	const locale = useSelector((state: ReduxStateType) => state.settings.language);
	const isImportedToken = token?.tags?.includes("imported") ?? false;

	// fetch balance for imported tokens
	const { balance: fetchedTokenBalance, isLoading: isFetchingBalance } =
		useTokenBalance({
			token,
			shouldFetch: isImportedToken,
		});

	const _tokenBalance = isImportedToken ? fetchedTokenBalance : token?.balance;
	if (!_tokenBalance) return null;

	const formattedBalance = formatValue(_tokenBalance, token.decimals);

	return (
		<div className="bn-flex bn-flex-col bn-items-end bn-text-right bn-aeonik-font bn-space-y-1">
			{token?.balanceInUsd ? (
				<p className="bn-text-primary bn-text-base bn-font-medium bn-leading-[18.2px] bn-text-nowrap bn-w-full">
					${abbreviateNumber(token.balanceInUsd, locale)}
				</p>
			) : null}

			{Boolean(formattedBalance !== "0") && (
				<Tooltip content={formattedBalance}>
					<p className="bn-text-secondary bn-text-sm bn-font-normal bn-leading-4 bn-text-nowrap bn-w-full">
						{adjustDecimals(formattedBalance, 3, locale)}
					</p>
				</Tooltip>
			)}
		</div>
	);
};
