import { useWeb3Modal } from '@web3modal/wagmi/react';
import { useAccount, useDisconnect } from 'wagmi';
import { Button, Space, Typography } from 'antd';
import { WalletOutlined, SwapOutlined, DisconnectOutlined, ReloadOutlined } from '@ant-design/icons';

const { Text } = Typography;

// 清理 WalletConnect 相关缓存和损坏的数据
const clearAllCache = () => {
  const keysToRemove: string[] = [];
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    if (
      key &&
      (key.startsWith('wc@') ||
        key.startsWith('wagmi') ||
        key.startsWith('@w3m') ||
        key.startsWith('@reown') ||
        key.includes('walletconnect') ||
        key.includes('WalletConnect') ||
        key.includes('appkit'))
    ) {
      keysToRemove.push(key);
    }
  }
  keysToRemove.forEach((key) => localStorage.removeItem(key));
  sessionStorage.clear();
};

export function ConnectButton() {
  const { open } = useWeb3Modal();
  const { address, isConnected, connector } = useAccount();
  const { disconnect } = useDisconnect();

  const formatAddress = (addr: string) => {
    return `${addr.slice(0, 6)}...${addr.slice(-4)}`;
  };

  // 断开连接并清理缓存，然后刷新页面
  const handleDisconnect = async () => {
    try {
      disconnect();
      await new Promise((resolve) => setTimeout(resolve, 100));
    } catch {
      // ignore
    }
    clearAllCache();
    // 设置跳过自动重连标记
    sessionStorage.setItem('skipReconnect', 'true');
    window.location.reload();
  };

  // 切换账户：弹出钱包账户选择
  const handleSwitchAccount = async () => {
    try {
      // 对于 injected 钱包（MetaMask 等），使用 wallet_requestPermissions
      if (
        connector?.id === 'injected' ||
        connector?.id === 'metaMask' ||
        connector?.id === 'io.metamask'
      ) {
        const provider = (await connector.getProvider()) as {
          request?: (args: { method: string; params?: unknown[] }) => Promise<unknown>;
        };
        if (provider?.request) {
          await provider.request({
            method: 'wallet_requestPermissions',
            params: [{ eth_accounts: {} }],
          });
          return;
        }
      }
    } catch (err) {
      console.log('Switch account error:', err);
    }
    // 失败或其他钱包：断开后重新连接
    try {
      disconnect();
      await new Promise((resolve) => setTimeout(resolve, 100));
    } catch {
      // ignore
    }
    clearAllCache();
    sessionStorage.setItem('skipReconnect', 'true');
    sessionStorage.setItem('autoOpenConnect', 'true');
    window.location.reload();
  };

  // 重置连接（清理缓存后刷新）
  const handleReset = () => {
    clearAllCache();
    window.location.reload();
  };

  if (isConnected && address) {
    return (
      <Space>
        <Text strong style={{ fontFamily: 'monospace' }} title={address}>
          {formatAddress(address)}
        </Text>
        <Button size="small" icon={<SwapOutlined />} onClick={handleSwitchAccount}>
          切换
        </Button>
        <Button
          size="small"
          danger
          icon={<DisconnectOutlined />}
          onClick={handleDisconnect}
        >
          断开
        </Button>
      </Space>
    );
  }

  return (
    <Space>
      <Button type="primary" icon={<WalletOutlined />} onClick={() => open()}>
        连接钱包
      </Button>
      <Button size="small" icon={<ReloadOutlined />} onClick={handleReset} title="强制连接">
        重置
      </Button>
    </Space>
  );
}
