import { Skeleton, TokenLogoWithChain } from "@src/components";
import { useSwapContext } from "@src/context";
import { TokenOption } from "@src/models";
import { weiToHumanReadable } from "@src/utils";
import { ethers } from "ethers";
import { useMemo } from "react";
import { useAccount } from "wagmi";

type Props = {
  token: TokenOption;
  selectedTokenAddress: string | undefined;
  onClick: () => void;
};
export const TokenItem = ({ token, selectedTokenAddress, onClick }: Props) => {
  const { supportedChains } = useSwapContext();
  const { address } = useAccount();

  const chain = useMemo(
    () => supportedChains.find(({ chainId }) => chainId === token.chainId),
    [supportedChains, token],
  );

  return (
    <div
      className={`token-picker-container ${
        token.address.toLowerCase() === selectedTokenAddress?.toLowerCase() &&
        "bg-t_bg_tertiary bg-opacity-10"
      }`}
      onClick={onClick}
    >
      <TokenLogoWithChain
        token={token}
        chain={chain}
        tokenLogoClassName="w-9"
        generatedLogoClassName="w-9 min-w-9 h-9 text-[16px]"
        chainLogoClassName="w-5"
      />
      <div className="flex justify-between items-center gap-1 w-full">
        <div className="text-left">
          <div className="text-sm font-medium text-ellipsis text-t_text_primary">
            {token.name}
          </div>
          <div className="text-xs text-t_text_primary text-opacity-50 font-medium">
            {chain?.displayName}
          </div>
        </div>

        {token.balance && token.decimals ? (
          <div className="text-xs text-t_text_primary text-opacity-50">
            {token.balance.eq(0) ||
            Number(ethers.utils.formatUnits(token.balance, token.decimals)) >
              0.0001
              ? weiToHumanReadable({
                  amount: token.balance.toString(),
                  decimals: token.decimals,
                  precisionFractionalPlaces: 4,
                })
              : "<0.0001"}
          </div>
        ) : address ? (
          <div>
            <Skeleton className="w-[48px] h-[12px]" />
          </div>
        ) : null}
      </div>
    </div>
  );
};
