import { useEffect } from 'react'
import { SSR } from '@/lib/constants'
import { WalletError } from '../errors'
export * from '@/wallets/webln'

export const sendPayment = async (bolt11) => {
  if (typeof window.webln === 'undefined') {
    throw new WalletError('WebLN provider not found')
  }

  // this will prompt the user to unlock the wallet if it's locked
  try {
    await window.webln.enable()
  } catch (err) {
    throw new WalletError(err.message)
  }

  // this will prompt for payment if no budget is set
  const response = await window.webln.sendPayment(bolt11)
  if (!response) {
    // sendPayment returns nothing if WebLN was enabled
    // but browser extension that provides WebLN was then disabled
    // without reloading the page
    throw new WalletError('sendPayment returned no response')
  }

  return response.preimage
}

export function isAvailable () {
  return !SSR && window?.weblnEnabled
}

export function WebLnProvider ({ children }) {
  useEffect(() => {
    const onEnable = () => {
      window.weblnEnabled = true
    }

    const onDisable = () => {
      window.weblnEnabled = false
    }

    if (!window.webln) onDisable()
    else onEnable()

    window.addEventListener('webln:enabled', onEnable)
    // event is not fired by Alby browser extension but added here for sake of completeness
    window.addEventListener('webln:disabled', onDisable)
    return () => {
      window.removeEventListener('webln:enabled', onEnable)
      window.removeEventListener('webln:disabled', onDisable)
    }
  }, [])

  return children
}
