import { useEffect, useState } from 'react'
import { toast } from 'react-toastify'
import { CreateSignatureEventContent, Meta } from '../types'
import { parseJson, formatTimestamp } from '../utils'
import { Event } from 'nostr-tools'

export enum SignedStatus {
  Partial = 'In-Progress',
  Complete = 'Completed'
}

export const useSigitMeta = (meta: Meta) => {
  const [title, setTitle] = useState<string>()
  const [createdAt, setCreatedAt] = useState('')
  const [submittedBy, setSubmittedBy] = useState<string>()
  const [signers, setSigners] = useState<`npub1${string}`[]>([])
  const [signedStatus, setSignedStatus] = useState<SignedStatus>(
    SignedStatus.Partial
  )
  const [fileExtensions, setFileExtensions] = useState<string[]>([])

  useEffect(() => {
    const extractInfo = async () => {
      const createSignatureEvent = await parseJson<Event>(
        meta.createSignature
      ).catch((err) => {
        console.log('err in parsing the createSignature event:>> ', err)
        toast.error(
          err.message || 'error occurred in parsing the create signature event'
        )
        return null
      })

      if (!createSignatureEvent) return

      // created_at in nostr events are stored in seconds
      // convert it to ms before formatting
      setCreatedAt(formatTimestamp(createSignatureEvent.created_at * 1000))

      const createSignatureContent =
        await parseJson<CreateSignatureEventContent>(
          createSignatureEvent.content
        ).catch((err) => {
          console.log(
            `err in parsing the createSignature event's content :>> `,
            err
          )
          return null
        })

      if (!createSignatureContent) return

      const files = Object.keys(createSignatureContent.fileHashes)
      const extensions = files.reduce((result: string[], file: string) => {
        const extension = file.split('.').pop()
        if (extension) {
          result.push(extension)
        }
        return result
      }, [])

      setTitle(createSignatureContent.title)
      setSubmittedBy(createSignatureEvent.pubkey)
      setSigners(createSignatureContent.signers)
      setFileExtensions(extensions)

      const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[]
      const isCompletelySigned = createSignatureContent.signers.every(
        (signer) => signedBy.includes(signer)
      )
      if (isCompletelySigned) {
        setSignedStatus(SignedStatus.Complete)
      }
    }
    extractInfo()
  }, [meta])

  return {
    title,
    createdAt,
    submittedBy,
    signers,
    signedStatus,
    fileExtensions
  }
}
