import { useEffect, useState } from 'react'

import { NDKUserProfile } from '@nostr-dev-kit/ndk'
import { useNDKContext } from './useNDKContext'

export const useProfileMetadata = (pubkey: string) => {
  const { findMetadata } = useNDKContext()

  const [userProfile, setUserProfile] = useState<NDKUserProfile>()

  useEffect(() => {
    if (pubkey) {
      findMetadata(pubkey)
        .then((profile) => {
          if (profile) setUserProfile(profile)
        })
        .catch((err) => {
          console.error(
            `error occurred in finding metadata for: ${pubkey}`,
            err
          )
        })
    }
  }, [pubkey, findMetadata])

  return userProfile
}
