import { useChainId, useSwitchChain, useAccount } from 'wagmi'
import { arbitrumSepolia, bscTestnet } from 'wagmi/chains'
import { Select, Tag } from 'antd'
import { ApiOutlined, WarningOutlined } from '@ant-design/icons'

const CHAINS = [
  {
    id: arbitrumSepolia.id,
    name: 'Arbitrum Sepolia',
    shortName: 'ARB',
    color: '#28A0F0',
  },
  {
    id: bscTestnet.id,
    name: 'BNB Testnet',
    shortName: 'BNB',
    color: '#F3BA2F',
  },
]

export function NetworkSwitch() {
  const { isConnected } = useAccount()
  const chainId = useChainId()
  const { switchChain, isPending } = useSwitchChain()

  if (!isConnected) return null

  const currentChain = CHAINS.find((c) => c.id === chainId)
  const isUnsupported = !currentChain

  return (
    <Select
      loading={isPending}
      value={isUnsupported ? undefined : chainId}
      placeholder={
        <span style={{ color: '#ff4d4f' }}>
          <WarningOutlined /> 不支持的网络
        </span>
      }
      onChange={(value) => switchChain({ chainId: value })}
      style={{ minWidth: 160 }}
      options={CHAINS.map((chain) => ({
        value: chain.id,
        label: (
          <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <Tag
              color={chain.color}
              style={{ margin: 0, fontSize: 10, lineHeight: '18px', padding: '0 4px' }}
            >
              {chain.shortName}
            </Tag>
            {chain.name}
          </span>
        ),
      }))}
      suffixIcon={isUnsupported ? <WarningOutlined style={{ color: '#ff4d4f' }} /> : <ApiOutlined />}
    />
  )
}
