import { getConnectorIcon } from 'nimbus-wallet-management';
import { ExpandMore, Wallet } from '@mui/icons-material';
import { Avatar, Badge } from '@mui/material';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import type { Account } from '../../hooks/useAccount.js';
import { useAccount } from '../../hooks/useAccount.js';
import { useChain } from '../../hooks/useChain.js';
import { useHasExternalWalletProvider } from '../../providers/WalletProvider/useHasExternalWalletProvider.js';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import { HiddenUI } from '../../types/widget.js';
import { navigationRoutes } from '../../utils/navigationRoutes.js';
import { shortenAddress } from '../../utils/wallet.js';
import { SmallAvatar } from '../SmallAvatar.js';
import { CloseDrawerButton } from './CloseDrawerButton.js';
import {
  DrawerWalletContainer,
  HeaderAppBar,
  WalletAvatar,
  WalletButton,
} from './Header.style.js';
import { WalletMenu } from './WalletMenu.js';
import { WalletMenuContainer } from './WalletMenu.style.js';
import { ChainType } from '../../utils/chainType.js';
// @ts-ignore
import { useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
import { useTon } from '../../providers/WalletProvider/TVM/TVMBaseProvider.js';
import { useDisconnect } from 'wagmi';
import { useFieldValues } from '../../stores/form/useFieldValues.js';
import { FormKeyHelper } from '../../stores/form/types.js';
import { ChainId } from '../../types/base.js';
import { useFieldActions } from '../../stores/form/useFieldActions.js';
import { getDefaultValuesFromQueryString } from '../../stores/form/URLSearchParamsBuilder.js';

export const WalletHeader: React.FC = () => {
  const { subvariant, hiddenUI } = useWidgetConfig();
  const { hasExternalProvider } = useHasExternalWalletProvider();
  return !hasExternalProvider &&
    subvariant !== 'split' &&
    !hiddenUI?.includes(HiddenUI.WalletMenu) ? (
    <HeaderAppBar elevation={0} sx={{ justifyContent: 'flex-end' }}>
      <WalletMenuButton />
    </HeaderAppBar>
  ) : null;
};

export const SplitWalletMenuButton: React.FC = () => {
  const { hiddenUI } = useWidgetConfig();
  const { hasExternalProvider } = useHasExternalWalletProvider();
  return !hasExternalProvider && !hiddenUI?.includes(HiddenUI.WalletMenu) ? (
    <WalletMenuButton />
  ) : null;
};

export const WalletMenuButton: React.FC = () => {
  const { account, accounts } = useAccount();
  const { variant, hiddenUI, isUniversalSwap } = useWidgetConfig();

  // TODO: remove when enable other chain
  const { tonConnectUI } = useTon();
  const { disconnect } = useSolanaWallet();
  const evmDisconnect = useDisconnect();

  const wait = (time: number) => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(true);
      }, time);
    });
  };

  const handleDisconnectWallet = async () => {
    if (account.isConnected && isUniversalSwap) {
      if (account.chainType === ChainType.EVM) {
        if (account?.connector?.name === 'MetaMask') {
          await wait(10000); // 10s
          evmDisconnect.disconnect({
            connector: account?.connector as any,
          });
        } else {
          evmDisconnect.disconnect({
            connector: account?.connector as any,
          });
        }
      }
    }
  };

  useEffect(() => {
    handleDisconnectWallet();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [account, isUniversalSwap, disconnect, tonConnectUI, evmDisconnect]);

  if (variant === 'drawer') {
    return (
      <DrawerWalletContainer>
        {account.isConnected ? (
          <ConnectedButton account={account} accounts={accounts} />
        ) : (
          <ConnectButton />
        )}
        {!hiddenUI?.includes(HiddenUI.DrawerCloseButton) ? (
          <CloseDrawerButton header="wallet" />
        ) : null}
      </DrawerWalletContainer>
    );
  }

  return account.isConnected ? (
    <ConnectedButton account={account} accounts={accounts} />
  ) : (
    <ConnectButton />
  );
};

const ConnectButton = () => {
  const { t } = useTranslation();
  const { pathname } = useLocation();
  const { walletConfig, subvariant, variant } = useWidgetConfig();
  const navigate = useNavigate();
  const connect = async () => {
    if (walletConfig?.onConnect) {
      walletConfig.onConnect();
      return;
    }
    navigate(navigationRoutes.selectWallet);
  };

  return (
    <WalletButton
      subvariant={subvariant}
      endIcon={
        variant !== 'drawer' && subvariant !== 'split' ? <Wallet /> : undefined
      }
      startIcon={
        variant === 'drawer' || subvariant === 'split' ? (
          <Wallet sx={{ marginLeft: -0.25 }} />
        ) : undefined
      }
      onClick={
        !pathname.includes(navigationRoutes.selectWallet) ? connect : undefined
      }
    >
      {t(`button.connectWallet`)}
    </WalletButton>
  );
};

const ConnectedButton = ({
  account,
  accounts,
}: {
  account: Account;
  accounts: Account[];
}) => {
  const [anchorEl, setAnchorEl] = useState<HTMLElement | null>(null);
  const { subvariant, fromToken } = useWidgetConfig();
  const [chainId] = useFieldValues(FormKeyHelper.getChainKey('from'));

  const { setUserAndDefaultValues } = useFieldActions();

  const selectedAccount =
    accounts.find((acc) => acc.chainId === chainId) || account;

  const { chain } = useChain(selectedAccount.chainId);
  const walletAddress = shortenAddress(selectedAccount.address);

  useEffect(() => {
    setTimeout(() => {
      const formValues = getDefaultValuesFromQueryString();

      if (!fromToken && !formValues.fromToken && !formValues.toToken) {
        if (chainId === ChainId.MOVE) {
          setUserAndDefaultValues({
            fromToken: '0x2::sui::SUI',
            toToken:
              '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN',
          });
        }
        if (chainId === ChainId.TON) {
          setUserAndDefaultValues({
            fromToken:
              '0:0000000000000000000000000000000000000000000000000000000000000000',
            toToken:
              '0:b113a994b5024a16719f69139328eb759596c38a25f59028b146fecdc3621dfe',
          });
        }
        if (chainId === ChainId.ECLIPSE) {
          setUserAndDefaultValues({
            fromToken: 'So11111111111111111111111111111111111111112',
            toToken: 'AKEWE7Bgh87GPp171b4cJPSSZfmZwQ3KaqYqXoKLNAEE',
          });
        }
        if (chainId === ChainId.SOL) {
          setUserAndDefaultValues({
            fromToken: '11111111111111111111111111111111',
            toToken: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
          });
        }
      }
    }, 0);
  }, [chainId, fromToken, setUserAndDefaultValues]);

  const handleClick = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  return (
    <>
      <WalletButton
        subvariant={subvariant}
        endIcon={<ExpandMore />}
        startIcon={
          chain?.logoURI ? (
            <Badge
              overlap="circular"
              anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
              badgeContent={
                <SmallAvatar
                  src={chain?.logoURI}
                  alt={chain?.name}
                  sx={{ width: 12, height: 12 }}
                >
                  {chain?.name[0]}
                </SmallAvatar>
              }
            >
              <WalletAvatar
                src={getConnectorIcon(selectedAccount.connector)}
                alt={selectedAccount.connector?.name}
              >
                {selectedAccount.connector?.name[0]}
              </WalletAvatar>
            </Badge>
          ) : (
            <Avatar
              src={getConnectorIcon(selectedAccount.connector)}
              alt={selectedAccount.connector?.name}
              sx={{ width: 24, height: 24 }}
            >
              {selectedAccount.connector?.name[0]}
            </Avatar>
          )
        }
        onClick={handleClick}
      >
        {walletAddress}
      </WalletButton>
      <WalletMenuContainer
        anchorEl={anchorEl}
        open={Boolean(anchorEl)}
        onClose={handleClose}
      >
        <WalletMenu onClose={handleClose} />
      </WalletMenuContainer>
    </>
  );
};
