import MessageView from '@/components/Inbox/MessageView'
import SecondaryPageLayout from '@/layouts/SecondaryPageLayout'
import { useSecondaryPage } from '@/PageManager'
import { useDM } from '@/providers/DMProvider'
import { TPageRef } from '@/types'
import { nip19 } from 'nostr-tools'
import { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from 'react'
import { useTranslation } from 'react-i18next'

interface DMConversationPageProps {
  pubkey?: string
  index?: number
}

const DMConversationPage = forwardRef<TPageRef, DMConversationPageProps>(({ pubkey, index }, ref) => {
  const { t } = useTranslation()
  const layoutRef = useRef<TPageRef>(null)
  const { selectConversation, currentConversation } = useDM()
  const { pop } = useSecondaryPage()

  // Decode npub to hex if needed
  const hexPubkey = useMemo(() => {
    if (!pubkey) return null
    if (pubkey.startsWith('npub')) {
      try {
        const decoded = nip19.decode(pubkey)
        return decoded.type === 'npub' ? decoded.data : null
      } catch {
        return null
      }
    }
    return pubkey
  }, [pubkey])

  useImperativeHandle(ref, () => layoutRef.current as TPageRef)

  // Select the conversation when this page mounts
  useEffect(() => {
    if (hexPubkey && hexPubkey !== currentConversation) {
      selectConversation(hexPubkey)
    }
  }, [hexPubkey, selectConversation, currentConversation])

  // Clear conversation when page unmounts
  useEffect(() => {
    return () => {
      selectConversation(null)
    }
  }, [])

  const handleBack = () => {
    selectConversation(null)
    pop()
  }

  return (
    <SecondaryPageLayout ref={layoutRef} index={index} title={t('Conversation')}>
      <div className="h-full">
        <MessageView onBack={handleBack} />
      </div>
    </SecondaryPageLayout>
  )
})

DMConversationPage.displayName = 'DMConversationPage'
export default DMConversationPage
