import { useState } from 'react'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { useArticlePublishing } from '@/hooks/useArticlePublishing'
import type { ArticleDraft } from '@/lib/articlePublisher'
import { ArticleEditorForm } from './ArticleEditorForm'

interface ArticleEditorProps {
  onPublishSuccess?: (articleId: string) => void
  onCancel?: () => void
  seriesOptions?: { id: string; title: string }[]
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
}


function SuccessMessage(): JSX.Element {
  return (
    <div className="border rounded-lg p-6 bg-green-50 border-green-200">
      <h3 className="text-lg font-semibold text-green-800 mb-2">Article Published!</h3>
      <p className="text-green-700">Your article has been successfully published.</p>
    </div>
  )
}

export function ArticleEditor({ onPublishSuccess, onCancel, seriesOptions, onSelectSeries }: ArticleEditorProps): JSX.Element {
  const { connected, pubkey, connect } = useNostrAuth()
  const { loading, error, success, publishArticle } = useArticlePublishing(pubkey ?? null)
  const [draft, setDraft] = useState<ArticleDraft>({
    title: '',
    preview: '',
    content: '',
    zapAmount: 800,
    media: [],
  })

  const submit = buildSubmitHandler(publishArticle, draft, onPublishSuccess, connect, connected)

  if (success) {
    return <SuccessMessage />
  }

  return (
    <ArticleEditorForm
      draft={draft}
      onDraftChange={setDraft}
      onSubmit={(e) => {
        e.preventDefault()
        void submit()
      }}
      loading={loading}
      error={error}
      {...(onCancel ? { onCancel } : {})}
      {...(seriesOptions ? { seriesOptions } : {})}
      {...(onSelectSeries ? { onSelectSeries } : {})}
    />
  )
}

function buildSubmitHandler(
  publishArticle: (draft: ArticleDraft) => Promise<string | null>,
  draft: ArticleDraft,
  onPublishSuccess?: (articleId: string) => void,
  connect?: () => Promise<void>,
  connected?: boolean
): () => Promise<void> {
  return async (): Promise<void> => {
    if (!connected && connect) {
      await connect()
      return
    }
    const articleId = await publishArticle(draft)
    if (articleId) {
      onPublishSuccess?.(articleId)
    }
  }
}
