import { usePrivy } from '@privy-io/react-auth'
import { useAccount, useConnect, useDisconnect } from 'wagmi'
import { useCallback, useEffect } from 'react'

/**
 * Custom hook to integrate Privy wallet with wagmi
 * This hook handles connecting and disconnecting the Privy wallet
 * and provides a simplified interface for wallet interactions
 */
export const usePrivyWallet = () => {
  const { user, ready, authenticated, login, logout } = usePrivy()
  const { isConnected } = useAccount()
  const { connectAsync, connectors } = useConnect()
  const { disconnectAsync } = useDisconnect()

  // Connect the wallet when the user is authenticated
  useEffect(() => {
    const connectWallet = async () => {
      if (ready && authenticated && user && !isConnected) {
        try {
          // Get the embedded wallet if available
          const embeddedWallet = user.wallet?.address ? user.wallet : null
          
          if (embeddedWallet && connectors.length > 0) {
            // Connect using the Privy connector
            // The Privy connector is automatically added by the Privy WagmiProvider
            const privyConnector = connectors.find(c => c.name === 'Privy') || connectors[0]
            
            await connectAsync({
              connector: privyConnector,
              chainId: 1 // Default to Ethereum mainnet
            })
          }
        } catch (error) {
          console.error('Failed to connect wallet:', error)
        }
      }
    }

    connectWallet()
  }, [ready, authenticated, user, isConnected, connectAsync, connectors])

  // Disconnect the wallet when the user logs out
  const handleLogout = useCallback(async () => {
    if (isConnected) {
      try {
        await disconnectAsync()
      } catch (error) {
        console.error('Failed to disconnect wallet:', error)
      }
    }
    logout()
  }, [isConnected, disconnectAsync, logout])

  return {
    isAuthenticated: authenticated,
    isConnected,
    isReady: ready,
    user,
    login,
    logout: handleLogout,
  }
}

export default usePrivyWallet 