import { DotGreenIcon } from "@src/assets/icons";
import { SwapPanelType } from "@src/components/Swap/SwapView";
import { useSwapContext } from "@src/context";
import useNetworks from "@src/hooks/networkManagement/useNetworks";
import { Chain } from "@src/models";
import { useMemo } from "react";

type Props = {
  chain: Chain;
  type: SwapPanelType;
  disabled: boolean;
  onClick: (chainId: string) => void;
};

export const ChainItem = ({ chain, type, onClick, disabled }: Props) => {
  const {
    networks: { evm },
  } = useNetworks();

  const { srcChain, dstChain, bridgeUI } = useSwapContext();

  const currentChainId = useMemo(
    () => (type === "source" ? srcChain?.chainId : dstChain?.chainId),
    [dstChain, srcChain, type],
  );

  const connected = useMemo(
    () => evm.signer && evm.chainId === chain.chainId,
    [chain.chainId, evm.chainId, evm.signer],
  );

  const sameChainId = useMemo(() => {
    if (!bridgeUI) {
      return undefined;
    }

    return type === "destination" ? srcChain?.chainId : dstChain?.chainId;
  }, [bridgeUI, dstChain?.chainId, srcChain?.chainId, type]);

  const getTooltipText = () => {
    if (chain.chainId === sameChainId) {
      return "Transfers between the same chains are not available";
    }
    if (disabled) {
      return bridgeUI
        ? "Token is not available on this chain"
        : `Swap from ${
            srcChain?.displayName || "the source chain"
          } to this chain is currently not supported.`;
    }
    return "";
  };

  const tooltipText = getTooltipText();

  return (
    <div className="group relative">
      <div
        onClick={() => {
          if (chain.chainId === sameChainId || disabled) {
            return;
          }
          onClick(chain.chainId);
        }}
        className={`flex justify-between items-center gap-2 mt-2 mb-2 cursor-pointer p-4 border border-solid border-white border-opacity-0 hover:selected-chain-item ${
          currentChainId === chain.chainId ? "selected-chain-item" : ""
        } ${
          chain.chainId === sameChainId || disabled
            ? "disabled-chain-item cursor-default"
            : ""
        }`}
      >
        <div className="flex gap-3 items-center w-full">
          <img
            src={chain.image}
            alt={chain.name}
            className="w-[34px] h-[34px]"
          />
          <p>{chain.displayName}</p>
        </div>

        {tooltipText && (
          <div className="w-full text-center opacity-0 group-hover:opacity-100 text-xs transition-opacity duration-200">
            {tooltipText}
          </div>
        )}

        {connected && (
          <div className="flex items-baseline gap-1">
            <DotGreenIcon />
            <div className="text-t_text_green">connected</div>
          </div>
        )}
      </div>
    </div>
  );
};
