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

interface ArticleEditorProps {
  onPublishSuccess?: (articleId: string) => void
  onCancel?: () => void
}

function NotConnectedMessage() {
  return (
    <div className="border rounded-lg p-6 bg-gray-50">
      <p className="text-center text-gray-600 mb-4">Please connect with Nostr to publish articles</p>
    </div>
  )
}

function SuccessMessage() {
  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 }: ArticleEditorProps) {
  const { connected, pubkey } = useNostrConnect()
  const { loading, error, success, publishArticle } = useArticlePublishing(pubkey ?? null)
  const [draft, setDraft] = useState<ArticleDraft>({
    title: '',
    preview: '',
    content: '',
    zapAmount: 800,
  })

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    const articleId = await publishArticle(draft)
    if (articleId) {
      onPublishSuccess?.(articleId)
    }
  }

  if (!connected) {
    return <NotConnectedMessage />
  }

  if (success) {
    return <SuccessMessage />
  }

  return (
    <ArticleEditorForm
      draft={draft}
      onDraftChange={setDraft}
      onSubmit={handleSubmit}
      loading={loading}
      error={error}
      onCancel={onCancel}
    />
  )
}
