import { getConnectorIcon } from 'nimbus-wallet-management';
import {
  ContentCopyRounded,
  OpenInNewRounded,
  PowerSettingsNewRounded,
} from '@mui/icons-material';
import {
  Avatar,
  Badge,
  Box,
  Button,
  IconButton,
  MenuItem,
} from '@mui/material';
import { useTranslation } from 'react-i18next';
import { useLocation, useNavigate } from 'react-router-dom';
import { useAccount } from '../../hooks/useAccount.js';
import { useAvailableChains } from '../../hooks/useAvailableChains.js';
import { useExplorer } from '../../hooks/useExplorer.js';
import { navigationRoutes } from '../../utils/navigationRoutes.js';
import { shortenAddress } from '../../utils/wallet.js';
import { AvatarMasked } from '../Avatar/Avatar.style.js';
import { SmallAvatar } from '../SmallAvatar.js';
import { EVMDisconnectIconButton } from './EVMDisconnectIconButton.js';
import { SVMDisconnectIconButton } from './SVMDisconnectIconButton.js';
import mixpanel from 'mixpanel-browser';
import { useWidgetConfig } from '../../providers/WidgetProvider/WidgetProvider.js';
import { TVMDisconnectIconButton } from './TVMDisconnectIconButton.js';
import { MVMDisconnectIconButton } from './MVMDisconnectIconButton.js';
import { ChainType } from '../../utils/chainType.js';
import { useTon } from '../../providers/WalletProvider/TVM/TVMBaseProvider.js';
// @ts-ignore
import { useWallet } from '@suiet/wallet-kit';
import { useWallet as useSolanaWallet } from '@solana/wallet-adapter-react';
import { useDisconnect } from 'wagmi';
import { useFieldActions } from '../../stores/form/useFieldActions.js';

export const WalletMenu = ({ onClose }: { onClose: () => void }) => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const { pathname } = useLocation();
  const { accounts } = useAccount();
  const { getChainById } = useAvailableChains();
  const { mixpanelToken, chains, isUniversalSwap } = useWidgetConfig();
  const { disconnect } = useSolanaWallet();
  const evmDisconnect = useDisconnect();
  const { setFieldValue } = useFieldActions();
  const suiWalletInstance = useWallet();
  const { tonConnectUI } = useTon();

  const findSuiAccount = accounts.find(
    (account) => account.chainType === ChainType.MVM,
  );

  const findTonAccount = accounts.find(
    (account) => account.chainType === ChainType.TVM,
  );

  const findSolAccount =
    accounts.find(
      (account) =>
        account.chainType === ChainType.SVM &&
        chains?.types?.allow?.includes(ChainType.SVM),
    ) || [];

  const findEclipseAccount =
    accounts.find(
      (account) =>
        account.chainType === ChainType.ECLIPSE &&
        chains?.types?.allow?.includes(ChainType.ECLIPSE),
    ) || [];

  const findEVMAccount = accounts.find(
    (account) => account.chainType === ChainType.EVM,
  );

  const connect = async () => {
    if (mixpanelToken) {
      mixpanel.track('universal_swap_select_connect_wallet');
    }

    if (!isUniversalSwap) {
      if (findTonAccount) {
        tonConnectUI?.disconnect();
      }

      if (findSuiAccount) {
        suiWalletInstance?.disconnect();
      }

      if (findSolAccount || findEclipseAccount) {
        disconnect();
      }

      if (findEVMAccount) {
        evmDisconnect.disconnect({
          connector: findEVMAccount?.connector as any,
        });
      }

      setFieldValue('fromToken', '', { isDirty: true, isTouched: true });
      setFieldValue('toToken', '', { isDirty: true, isTouched: true });
    }

    navigate(navigationRoutes.selectWallet);
    onClose();
  };

  const { getAddressLink } = useExplorer();

  return (
    <>
      <Box display="flex" flexDirection="column">
        {accounts
          .filter(
            (item) =>
              ![ChainType.SVM, ChainType.ECLIPSE].includes(
                item.chainType as any,
              ),
          )
          .concat(findEclipseAccount)
          .concat(findSolAccount)
          .map((account) => {
            const chain = getChainById(account.chainId);
            const walletAddress = shortenAddress(account.address);
            const handleCopyAddress = async () => {
              await navigator.clipboard.writeText(account.address ?? '');
              onClose();
            };

            return (
              <MenuItem key={`${account.address}-${account.chainType}`}>
                <Box flex={1} display="flex" alignItems="center">
                  {chain?.logoURI ? (
                    <Badge
                      overlap="circular"
                      anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
                      badgeContent={
                        <SmallAvatar src={chain?.logoURI} alt={chain?.name}>
                          {chain?.name[0]}
                        </SmallAvatar>
                      }
                      sx={{ marginRight: 1.5 }}
                    >
                      <AvatarMasked
                        src={getConnectorIcon(account.connector)}
                        alt={account.connector?.name}
                      >
                        {account.connector?.name[0]}
                      </AvatarMasked>
                    </Badge>
                  ) : (
                    <Avatar
                      src={getConnectorIcon(account.connector)}
                      alt={account.connector?.name}
                      sx={{
                        marginRight: 1.5,
                      }}
                    >
                      {account.connector?.name[0]}
                    </Avatar>
                  )}
                  {walletAddress}
                </Box>

                <Box ml={1}>
                  <IconButton size="medium" onClick={handleCopyAddress}>
                    <ContentCopyRounded />
                  </IconButton>

                  <IconButton
                    size="medium"
                    component="a"
                    onClick={onClose}
                    href={
                      account.address
                        ? getAddressLink(account.address, chain, true)
                        : undefined
                    }
                    target="_blank"
                  >
                    <OpenInNewRounded />
                  </IconButton>

                  {account.chainType === ChainType.EVM ? (
                    <EVMDisconnectIconButton connector={account.connector} />
                  ) : account.chainType === ChainType.SVM ||
                    account.chainType === ChainType.ECLIPSE ? (
                    <SVMDisconnectIconButton />
                  ) : account.chainType === ChainType.TVM ? (
                    <TVMDisconnectIconButton />
                  ) : account.chainType === ChainType.MVM ? (
                    <MVMDisconnectIconButton />
                  ) : null}
                </Box>
              </MenuItem>
            );
          })}
      </Box>

      {!pathname.includes(navigationRoutes.selectWallet) ? (
        <Button
          onClick={connect}
          fullWidth
          startIcon={<PowerSettingsNewRounded />}
          sx={{
            marginTop: 1,
          }}
        >
          {accounts.length > 1
            ? t(`button.changeWallet`)
            : t(`button.connectWallet`)}{' '}
        </Button>
      ) : null}
    </>
  );
};
