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'

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 (
      <Link
        href="/presentation"
        className="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"
      >
        {t('nav.createAuthorPage')}
      </Link>
    )
  }

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

  if (!hasPresentation) {
    return (
      <Link
        href="/presentation"
        className="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"
      >
        {t('nav.createAuthorPage')}
      </Link>
    )
  }

  return (
    <Link
      href="/publish"
      className="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"
    >
      {t('nav.publish')}
    </Link>
  )
}
