import { StarsIcon } from "@src/assets/icons";
import { Skeleton, TokenLogoWithChain } from "@src/components";
import { SwapPanelType } from "@src/components/Swap/SwapView";
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;
  selectedChainId: string | undefined;
  onClick: () => void;
  panelType: SwapPanelType;
};
export const TokenItem = ({
  token,
  selectedTokenAddress,
  onClick,
  selectedChainId,
  panelType,
}: Props) => {
  const {
    supportedChains,
    tokenPrices,
    isFetchingBalances,
    integrationConfig,
  } = useSwapContext();
  const { address } = useAccount();

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

  const tokenPrice = useMemo(() => {
    const prices = tokenPrices[token.chainId];
    return prices?.[token.address];
  }, [token, tokenPrices]);

  const tokenBalance = useMemo(() => {
    if (!token.balance || !token.decimals) return null;
    return Number(ethers.utils.formatUnits(token.balance, token.decimals));
  }, [token.balance, token.decimals]);

  const hasBalance = useMemo(
    () => token.balance && !token.balance.eq(0),
    [token.balance],
  );

  const tokenValueUsd = useMemo(() => {
    if (!tokenBalance || !tokenPrice || !hasBalance) return null;
    return tokenBalance * +tokenPrice;
  }, [tokenBalance, tokenPrice, hasBalance]);

  return (
    <div
      className={`token-picker-container ${
        token.address.toLowerCase() === selectedTokenAddress?.toLowerCase() &&
        selectedChainId &&
        token.chainId === selectedChainId
          ? "bg-t_bg_tertiary bg-opacity-10"
          : ""
      }`}
      onClick={onClick}
    >
      <TokenLogoWithChain
        token={token}
        chain={chain}
        tokenLogoClassName="min-w-9 w-9 h-9"
        generatedLogoClassName="min-w-9 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 flex items-center gap-1">
            {token.name}
            {integrationConfig?.highlightedDstTokens?.includes(token.symbol) &&
              panelType === "destination" && (
                <div
                  className={`flex items-center justify-center text-white rounded-full border-t_bg_secondary ${"w-3.5 h-3.5 text-xs"}`}
                  title="AI-powered token"
                >
                  <StarsIcon />
                </div>
              )}
          </div>
          <div className="text-xs text-t_text_primary text-opacity-50 font-medium">
            {token.symbol}
          </div>
        </div>
        {token.balance && token.decimals && address && !isFetchingBalances && (
          <div className="text-right">
            <div className="text-xs text-t_text_primary">
              {token.balance.eq(0) || tokenBalance! > 0.0001
                ? weiToHumanReadable({
                    amount: token.balance.toString(),
                    decimals: token.decimals,
                    precisionFractionalPlaces: 4,
                  })
                : "<0.0001"}
            </div>
            {hasBalance && (
              <div className="text-xs text-t_text_primary text-opacity-50">
                {tokenValueUsd ? `$${tokenValueUsd.toFixed(2)}` : "$ -"}
              </div>
            )}
          </div>
        )}

        {address && isFetchingBalances && (
          <div>
            <Skeleton className="w-[48px] h-[12px]" />
          </div>
        )}
      </div>
    </div>
  );
};
