import { useState, useEffect } from 'react'
import { Card } from './ui'
import { useToast } from './ui/ToastContainer'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { useArticlePublishing } from '@/hooks/useArticlePublishing'
import type { ArticleDraft } from '@/lib/articlePublisher'
import { ArticleEditorForm } from './ArticleEditorForm'
import { t } from '@/lib/i18n'

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

function SuccessMessage(): React.ReactElement {
  return (
    <Card variant="default" className="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>
    </Card>
  )
}

function usePublishSuccessToast(success: boolean, showToast: (message: string, variant?: 'success' | 'info' | 'warning' | 'error', duration?: number) => void, onPublishSuccess: ((articleId: string) => void) | undefined, draftTitle: string): void {
  useEffect(() => {
    if (success) {
      showToast(t('article.publish.success'), 'success')
      onPublishSuccess?.(draftTitle)
    }
  }, [success, showToast, onPublishSuccess, draftTitle])
}

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

  usePublishSuccessToast(success, showToast, onPublishSuccess, draft.title)

  const submit = buildSubmitHandler({
    publishArticle,
    draft,
    ...(onPublishSuccess ? { onPublishSuccess } : {}),
    connect,
    connected,
  })

  if (success) {
    return <SuccessMessage />
  }

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

interface SubmitHandlerParams {
  publishArticle: (draft: ArticleDraft) => Promise<string | null>
  draft: ArticleDraft
  onPublishSuccess?: (articleId: string) => void
  connect?: () => Promise<void>
  connected?: boolean
}

function buildSubmitHandler(
  params: SubmitHandlerParams
): () => Promise<void> {
  return async (): Promise<void> => {
    if (!params.connected && params.connect) {
      await params.connect()
      return
    }
    const articleId = await params.publishArticle(params.draft)
    if (articleId) {
      params.onPublishSuccess?.(articleId)
    }
  }
}
