import { useAccount } from 'wagmi'
import { useEffect, useRef } from 'react'
import toast from 'react-hot-toast'

/**
 * Shows a toast when the wallet disconnects unexpectedly (e.g. MetaMask extension
 * "Lost connection to MetaMask background"). Does not show when the user clicked Disconnect.
 */
export default function WalletDisconnectNotice({
  userInitiatedDisconnectRef,
}: {
  userInitiatedDisconnectRef: React.MutableRefObject<boolean>
}) {
  const { isConnected } = useAccount()
  const wasConnectedRef = useRef(false)

  useEffect(() => {
    if (wasConnectedRef.current && !isConnected) {
      if (userInitiatedDisconnectRef.current) {
        userInitiatedDisconnectRef.current = false
      } else {
        toast.error('Wallet disconnected. Please reconnect or reload the page.', { duration: 6000 })
      }
    }
    wasConnectedRef.current = isConnected
  }, [isConnected, userInitiatedDisconnectRef])

  return null
}
