import { useEffect, useCallback } from 'react'
import { useRouter } from 'next/router'
import Head from 'next/head'
import { PageHeader } from '@/components/PageHeader'
import { Footer } from '@/components/Footer'
import { AuthorPresentationEditor } from '@/components/AuthorPresentationEditor'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { useAuthorPresentation } from '@/hooks/useAuthorPresentation'
import { t } from '@/lib/i18n'

function usePresentationRedirect(connected: boolean, pubkey: string | null) {
  const router = useRouter()
  const { checkPresentationExists } = useAuthorPresentation(pubkey ?? null)

  const redirectIfExists = useCallback(async () => {
    if (!connected || !pubkey) {
      return
    }
    const presentation = await checkPresentationExists()
    if (presentation) {
      await router.push('/')
    }
  }, [checkPresentationExists, connected, pubkey, router])

  useEffect(() => {
    void redirectIfExists()
  }, [redirectIfExists])
}

function PresentationLayout() {
  return (
    <>
      <Head>
        <title>{t('presentation.title')} - {t('home.title')}</title>
        <meta
          name="description"
          content={t('presentation.description')}
        />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className="min-h-screen bg-cyber-darker">
        <PageHeader />
        <div className="max-w-4xl mx-auto px-4 py-8">
          <div className="mb-6">
            <h2 className="text-3xl font-bold text-neon-cyan font-mono mb-2">{t('presentation.title')}</h2>
            <p className="text-cyber-accent mt-2">
              {t('presentation.description')}
            </p>
          </div>

          <AuthorPresentationEditor />
        </div>
        <Footer />
      </main>
    </>
  )
}

export default function PresentationPage() {
  const { connected, pubkey } = useNostrAuth()
  usePresentationRedirect(connected, pubkey)
  return <PresentationLayout />
}
