import { useEffect, useState } from 'react'
import { ProfileMetadata } from '../types/profile'
import { MetadataController } from '../controllers/MetadataController'
import { Event, kinds } from 'nostr-tools'

export const useProfileMetadata = (pubkey: string) => {
  const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()

  useEffect(() => {
    const metadataController = MetadataController.getInstance()
    const handleMetadataEvent = (event: Event) => {
      const metadataContent =
        metadataController.extractProfileMetadataContent(event)

      if (metadataContent) {
        setProfileMetadata(metadataContent)
      }
    }

    if (pubkey) {
      metadataController.on(pubkey, (kind: number, event: Event) => {
        if (kind === kinds.Metadata) {
          handleMetadataEvent(event)
        }
      })

      metadataController
        .findMetadata(pubkey)
        .then((metadataEvent) => {
          if (metadataEvent) handleMetadataEvent(metadataEvent)
        })
        .catch((err) => {
          console.error(
            `error occurred in finding metadata for: ${pubkey}`,
            err
          )
        })
    }

    return () => {
      metadataController.off(pubkey, handleMetadataEvent)
    }
  }, [pubkey])

  return profileMetadata
}
