import React, { useState } from 'react'
import { Card, ErrorState } from './ui'
import type { ArticleDraft } from '@/lib/articlePublisher'
import { ArticleFormButtons } from './ArticleFormButtons'
import type { RelayPublishStatus } from '@/lib/publishResult'
import { t } from '@/lib/i18n'
import { ArticleFieldsLeft } from './ArticleEditorFormFieldsLeft'
import { ArticleFieldsRight } from './ArticleEditorFormFieldsRight'
import { ArticlePreviewModal } from './ArticlePreviewModal'

interface ArticleEditorFormProps {
  draft: ArticleDraft
  onDraftChange: (draft: ArticleDraft) => void
  onSubmit: (e: React.FormEvent) => void
  loading: boolean
  error: string | null
  relayStatuses?: RelayPublishStatus[]
  onCancel?: () => void
  seriesOptions?: { id: string; title: string }[] | undefined
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
}

function ErrorAlert({ error }: { error: string | null }): React.ReactElement | null {
  if (!error) {
    return null
  }
  return <ErrorState message={error} className="bg-red-50 border-red-200 text-red-800" />
}

function usePreviewModal(): {
  showPreview: boolean
  openPreview: () => void
  closePreview: () => void
} {
  const [showPreview, setShowPreview] = useState(false)
  return {
    showPreview,
    openPreview: () => {
      setShowPreview(true)
    },
    closePreview: () => {
      setShowPreview(false)
    },
  }
}

export function ArticleEditorForm({
  draft,
  onDraftChange,
  onSubmit,
  loading,
  error,
  relayStatuses,
  onCancel,
  seriesOptions,
  onSelectSeries,
}: ArticleEditorFormProps): React.ReactElement {
  const { showPreview, openPreview, closePreview } = usePreviewModal()

  return (
    <>
      <Card variant="default" className="bg-white">
        <form onSubmit={onSubmit} className="space-y-4">
          <h2 className="text-2xl font-bold mb-4">{t('article.editor.title')}</h2>
          <div className="space-y-4">
            <ArticleFieldsLeft
              draft={draft}
              onDraftChange={onDraftChange}
              {...(seriesOptions ? { seriesOptions } : {})}
              {...(onSelectSeries ? { onSelectSeries } : {})}
            />
            <ArticleFieldsRight draft={draft} onDraftChange={onDraftChange} />
          </div>
          <ErrorAlert error={error} />
          <ArticleFormButtons
            loading={loading}
            relayStatuses={relayStatuses}
            onPreview={openPreview}
            {...(onCancel ? { onCancel } : {})}
          />
        </form>
      </Card>
      <ArticlePreviewModal isOpen={showPreview} onClose={closePreview} draft={draft} />
    </>
  )
}
