import Link from 'next/link'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { useAuthorPresentation } from '@/hooks/useAuthorPresentation'
import { useEffect, useState } from 'react'
import { t } from '@/lib/i18n'

const buttonClassName = 'px-4 py-2 bg-neon-cyan/20 hover:bg-neon-cyan/30 text-neon-cyan rounded-lg text-sm font-medium transition-all border border-neon-cyan/50 hover:shadow-glow-cyan'

function CreateAuthorPageLink() {
  return (
    <Link href="/presentation" className={buttonClassName}>
      {t('nav.createAuthorPage')}
    </Link>
  )
}

function PublishLink() {
  return (
    <Link href="/publish" className={buttonClassName}>
      {t('nav.publish')}
    </Link>
  )
}

function LoadingButton() {
  return (
    <div className="px-4 py-2 bg-neon-cyan/20 text-neon-cyan rounded-lg text-sm font-medium">
      {t('nav.loading')}
    </div>
  )
}

export function ConditionalPublishButton() {
  const { connected, pubkey } = useNostrAuth()
  const { checkPresentationExists } = useAuthorPresentation(pubkey ?? null)
  const [hasPresentation, setHasPresentation] = useState<boolean | null>(null)

  useEffect(() => {
    const check = async () => {
      if (!connected || !pubkey) {
        setHasPresentation(null)
        return
      }
      const presentation = await checkPresentationExists()
      setHasPresentation(presentation !== null)
    }
    void check()
  }, [connected, pubkey, checkPresentationExists])

  if (!connected || !pubkey) {
    return <CreateAuthorPageLink />
  }

  if (hasPresentation === null) {
    return <LoadingButton />
  }

  if (!hasPresentation) {
    return <CreateAuthorPageLink />
  }

  return <PublishLink />
}
