import React from 'react'
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'

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 (
    <div className="bg-red-50 border border-red-200 rounded-lg p-3">
      <p className="text-sm text-red-800">{error}</p>
    </div>
  )
}

export function ArticleEditorForm({
  draft,
  onDraftChange,
  onSubmit,
  loading,
  error,
  relayStatuses,
  onCancel,
  seriesOptions,
  onSelectSeries,
}: ArticleEditorFormProps): React.ReactElement {
  return (
    <form onSubmit={onSubmit} className="border rounded-lg p-6 bg-white 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} {...(onCancel ? { onCancel } : {})} />
    </form>
  )
}
