import Head from 'next/head'
import { useRouter } from 'next/router'
import { ArticleEditor } from '@/components/ArticleEditor'
import { useEffect, useState } from 'react'
import { useNostrConnect } from '@/hooks/useNostrConnect'
import { getSeriesByAuthor } from '@/lib/seriesQueries'

function PublishHeader() {
  return (
    <Head>
      <title>Publish Article - zapwall.fr</title>
      <meta name="description" content="Publish a new article with free preview and paid content" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
    </Head>
  )
}

function PublishHero({ onBack }: { onBack: () => void }) {
  return (
    <div className="mb-6">
      <button
        onClick={onBack}
        className="text-blue-600 hover:text-blue-700 text-sm font-medium mb-4"
      >
        ← Back to Articles
      </button>
      <h2 className="text-3xl font-bold">Publish New Article</h2>
      <p className="text-gray-600 mt-2">Create an article with a free preview and paid full content</p>
    </div>
  )
}

export default function PublishPage() {
  const router = useRouter()
  const { pubkey } = useNostrConnect()
  const [seriesOptions, setSeriesOptions] = useState<{ id: string; title: string }[]>([])

  const handlePublishSuccess = () => {
    setTimeout(() => {
      void router.push('/')
    }, 2000)
  }

  useEffect(() => {
    if (!pubkey) {
      setSeriesOptions([])
      return
    }
    const load = async () => {
      const items = await getSeriesByAuthor(pubkey)
      setSeriesOptions(items.map((s) => ({ id: s.id, title: s.title })))
    }
    void load()
  }, [pubkey])

  return (
    <>
      <PublishHeader />
      <PublishLayout
        onBack={() => {
          void router.push('/')
        }}
        onPublishSuccess={handlePublishSuccess}
        seriesOptions={seriesOptions}
      />
    </>
  )
}

function PublishLayout({
  onBack,
  onPublishSuccess,
  seriesOptions,
}: {
  onBack: () => void
  onPublishSuccess: () => void
  seriesOptions: { id: string; title: string }[]
}) {
  return (
    <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>
        </div>
      </header>

      <div className="max-w-4xl mx-auto px-4 py-8">
        <PublishHero onBack={onBack} />
        <ArticleEditor onPublishSuccess={onPublishSuccess} seriesOptions={seriesOptions} />
      </div>
    </main>
  )
}
