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

type npub = `npub1${string}`

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

export interface SigitInfo {
  createdAt?: number
  title?: string
  submittedBy?: string
  signers: npub[]
  fileExtensions: string[]
  signedStatus: SignedStatus
}

export const extractSigitInfo = async (meta: Meta) => {
  if (!meta?.createSignature) return

  const sigitInfo: SigitInfo = {
    signers: [],
    fileExtensions: [],
    signedStatus: SignedStatus.Partial
  }

  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
  })

  if (!createSignatureEvent) return

  // created_at in nostr events are stored in seconds
  sigitInfo.createdAt = 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
  })

  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
  }, [])

  const signedBy = Object.keys(meta.docSignatures) as npub[]
  const isCompletelySigned = createSignatureContent.signers.every((signer) =>
    signedBy.includes(signer)
  )

  sigitInfo.title = createSignatureContent.title
  sigitInfo.submittedBy = createSignatureEvent.pubkey
  sigitInfo.signers = createSignatureContent.signers
  sigitInfo.fileExtensions = extensions

  if (isCompletelySigned) {
    sigitInfo.signedStatus = SignedStatus.Complete
  }

  return sigitInfo
}

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

  useEffect(() => {
    const getSigitInfo = async () => {
      const sigitInfo = await extractSigitInfo(meta)

      if (!sigitInfo) return

      setTitle(sigitInfo.title)
      setCreatedAt(sigitInfo.createdAt)
      setSubmittedBy(sigitInfo.submittedBy)
      setSigners(sigitInfo.signers)
      setSignedStatus(sigitInfo.signedStatus)
      setFileExtensions(sigitInfo.fileExtensions)
    }

    getSigitInfo()
  }, [meta])

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