import { usePrivy } from '@privy-io/react-auth'
import { useAccount, useBalance, useChainId, useSwitchChain } from 'wagmi'
import { arbitrum, mainnet } from 'viem/chains'
import { useCallback } from 'react'

/**
 * Component to display wallet information and test the Privy integration
 */
export const WalletInfo = () => {
  const { user, ready, authenticated, login, logout } = usePrivy()
  const { address, isConnected } = useAccount()
  const chainId = useChainId()
  const { data: balance } = useBalance({
    address,
  })
  const { switchChainAsync } = useSwitchChain()

  const switchToEthereum = useCallback(async () => {
    if (chainId !== mainnet.id) {
      try {
        await switchChainAsync({ chainId: mainnet.id })
      } catch (error) {
        console.error('Failed to switch to Ethereum:', error)
      }
    }
  }, [chainId, switchChainAsync])

  const switchToArbitrum = useCallback(async () => {
    if (chainId !== arbitrum.id) {
      try {
        await switchChainAsync({ chainId: arbitrum.id })
      } catch (error) {
        console.error('Failed to switch to Arbitrum:', error)
      }
    }
  }, [chainId, switchChainAsync])

  if (!ready) {
    return <div>Loading...</div>
  }

  if (!authenticated) {
    return (
      <div className="p-4 border rounded-lg shadow-sm">
        <h2 className="text-xl font-bold mb-4">Wallet Connection</h2>
        <p className="mb-4">Please connect your wallet to continue.</p>
        <button
          onClick={login}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
        >
          Connect Wallet
        </button>
      </div>
    )
  }

  return (
    <div className="p-4 border rounded-lg shadow-sm">
      <h2 className="text-xl font-bold mb-4">Wallet Information</h2>
      
      <div className="mb-4">
        <p><strong>Connected:</strong> {isConnected ? 'Yes' : 'No'}</p>
        <p><strong>Address:</strong> {address ? address : 'Not connected'}</p>
        <p><strong>Chain:</strong> {chainId === mainnet.id ? 'Ethereum' : chainId === arbitrum.id ? 'Arbitrum' : chainId}</p>
        <p><strong>Balance:</strong> {balance ? `${balance.formatted} ${balance.symbol}` : 'Unknown'}</p>
      </div>

      <div className="flex space-x-2 mb-4">
        <button
          onClick={switchToEthereum}
          className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          disabled={chainId === mainnet.id}
        >
          Switch to Ethereum
        </button>
        <button
          onClick={switchToArbitrum}
          className="px-4 py-2 bg-purple-500 text-white rounded hover:bg-purple-600"
          disabled={chainId === arbitrum.id}
        >
          Switch to Arbitrum
        </button>
      </div>

      <button
        onClick={logout}
        className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
      >
        Disconnect
      </button>
    </div>
  )
}

export default WalletInfo 