import { useEffect, useCallback } from 'react'
import { useRouter } from 'next/router'
import Head from 'next/head'
import { ConnectButton } from '@/components/ConnectButton'
import { AuthorPresentationEditor } from '@/components/AuthorPresentationEditor'
import { useNostrConnect } from '@/hooks/useNostrConnect'
import { useAuthorPresentation } from '@/hooks/useAuthorPresentation'

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>Créer votre article de présentation - zapwall4Science</title>
        <meta
          name="description"
          content="Créez votre article de présentation obligatoire pour publier sur zapwall4Science"
        />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>

      <main className="min-h-screen bg-gray-50">
        <header className="bg-white shadow-sm">
          <div className="max-w-4xl mx-auto px-4 py-4 flex justify-between items-center">
            <h1 className="text-2xl font-bold text-gray-900">zapwall4Science</h1>
            <ConnectButton />
          </div>
        </header>

        <div className="max-w-4xl mx-auto px-4 py-8">
          <div className="mb-6">
            <h2 className="text-3xl font-bold">Créer votre article de présentation</h2>
            <p className="text-gray-600 mt-2">
              Cet article est obligatoire pour publier sur zapwall4Science. Il permet aux
              lecteurs de vous connaître et de vous sponsoriser.
            </p>
          </div>

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

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