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

/**
 * Extracts profiles from metadata events
 * @param pubkeys Array of npubs to check
 * @returns ProfileMetadata
 */
export const useSigitProfiles = (
  pubkeys: `npub1${string}`[]
): { [key: string]: ProfileMetadata } => {
  const [profileMetadata, setProfileMetadata] = useState<{
    [key: string]: ProfileMetadata
  }>({})

  useEffect(() => {
    if (pubkeys.length) {
      const metadataController = new MetadataController()

      // Remove duplicate keys
      const users = new Set<string>([...pubkeys])

      const handleMetadataEvent = (key: string) => (event: Event) => {
        const metadataContent =
          metadataController.extractProfileMetadataContent(event)

        if (metadataContent) {
          setProfileMetadata((prev) => ({
            ...prev,
            [key]: metadataContent
          }))
        }
      }

      users.forEach((user) => {
        const hexKey = npubToHex(user)
        if (hexKey && !(hexKey in profileMetadata)) {
          metadataController.on(hexKey, (kind: number, event: Event) => {
            if (kind === kinds.Metadata) {
              handleMetadataEvent(hexKey)(event)
            }
          })

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

      return () => {
        users.forEach((key) => {
          metadataController.off(key, handleMetadataEvent(key))
        })
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pubkeys])

  return profileMetadata
}
