import { ArrowDownIcon } from "@src/assets/icons";
import { Modal, TokenLogo } from "@src/components";
import { useSwapContext } from "@src/context";
import { Chain, Token, TokenOption } from "@src/models";
import { useMemo, useState } from "react";
import { SwapPanelType } from "../../index";
import { TokenPicker } from "./TokenPicker";

type Props = {
  chain: Chain | undefined;
  token: Token | undefined;
  type: SwapPanelType;
  className?: string;
};

export const TokenPanel = ({ chain, token, type, className }: Props) => {
  const {
    bridgeUI,
    srcChainTokensOptions,
    srcChainOtherTokensOptions,
    dstChainTokensOptions,
    dstChainOtherTokensOptions,
    setSrcToken,
    setSrcChain,
    supportedChains,
    setDstToken,
    setDstChain,
    dstTokenLocked,
    srcTokenLocked,
  } = useSwapContext();

  const integratorLockedDestinationToken = useMemo(
    () => type === "destination" && dstTokenLocked,
    [type, dstTokenLocked],
  );

  const integratorLockedSourceToken = useMemo(
    () => type === "source" && srcTokenLocked,
    [type, srcTokenLocked],
  );

  const [tokenPickerModalOpen, setTokenPickerModalOpen] = useState(false);

  const tokensWithBalances = useMemo(
    () => (type === "source" ? srcChainTokensOptions : dstChainTokensOptions),
    [dstChainTokensOptions, srcChainTokensOptions, type],
  );

  const pickerDisabled = useMemo(
    () => type === "destination" && bridgeUI,
    [bridgeUI, type],
  );

  const otherTokensWithBalances = useMemo(
    () =>
      type === "source"
        ? srcChainOtherTokensOptions
        : dstChainOtherTokensOptions,
    [dstChainOtherTokensOptions, srcChainOtherTokensOptions, type],
  );

  const onTokenSelect = (token: TokenOption) => {
    const newChain = supportedChains.find(
      (chain) => chain.chainId === token.chainId,
    );

    if (type === "source") {
      setSrcToken(token);
      setSrcChain(newChain);
    } else {
      setDstToken(token);
      setDstChain(newChain);
    }
    setTokenPickerModalOpen(false);
  };

  return (
    <>
      {tokenPickerModalOpen && (
        <Modal onClose={() => setTokenPickerModalOpen(false)} className="z-[3]">
          <TokenPicker
            type={type}
            chain={chain!}
            tokens={tokensWithBalances}
            otherTokens={otherTokensWithBalances}
            selectedTokenAddress={token?.address}
            onSelect={onTokenSelect}
            isOpen={tokenPickerModalOpen}
            setModalOpen={setTokenPickerModalOpen}
          />
        </Modal>
      )}

      <button
        type="button"
        disabled={
          pickerDisabled ||
          integratorLockedDestinationToken ||
          integratorLockedSourceToken
        }
        onClick={() => {
          setTokenPickerModalOpen(true);
        }}
        className={`${className || ""}`}
      >
        <div className="flex justify-between items-center p-4 gap-8 border-r border-solid border-t_text_primary border-opacity-10">
          <div className="flex gap-2 items-center">
            <TokenLogo
              token={token}
              className="w-9 h-9"
              generatedLogoClassName="w-9 h-9 text-[16px]"
            />
            <div className="flex flex-col font-medium items-start">
              <p className="text-xs opacity-60">Token: </p>
              <p className={`${token ? "" : "opacity-60"}`}>
                {token
                  ? token.symbol
                  : type === "destination" && bridgeUI
                  ? "-"
                  : "Select"}
              </p>
            </div>
          </div>
          {!pickerDisabled &&
            !integratorLockedDestinationToken &&
            !integratorLockedSourceToken && (
              <div className="w-4 h-2 fill-t_text_primary">
                <ArrowDownIcon />
              </div>
            )}
        </div>
      </button>
    </>
  );
};
