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

function PublishHeader() {
  return (
    <Head>
      <title>{t('publish.title')} - {t('home.title')}</title>
      <meta name="description" content={t('publish.description')} />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
    </Head>
  )
}

function PublishHero({ onBack }: { onBack: () => void }): JSX.Element {
  return (
    <div className="mb-6">
      <button
        onClick={onBack}
        className="text-blue-600 hover:text-blue-700 text-sm font-medium mb-4"
      >
        {t('publish.back')}
      </button>
      <h2 className="text-3xl font-bold">{t('publish.title')}</h2>
      <p className="text-gray-600 mt-2">{t('publish.description')}</p>
    </div>
  )
}

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

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

  useEffect(() => {
    if (!pubkey) {
      setSeriesOptions([])
      return
    }
    const load = async (): Promise<void> => {
      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 }[]
}): JSX.Element {
  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>
  )
}
