import React from 'react'
import type { ArticleDraft } from '@/lib/articlePublisher'
import type { ArticleCategory } from '@/types/nostr'
import { ArticleField } from './ArticleField'
import { ArticleFormButtons } from './ArticleFormButtons'
import { CategorySelect } from './CategorySelect'
import { MarkdownEditor } from './MarkdownEditor'
import { MarkdownEditorTwoColumns } from './MarkdownEditorTwoColumns'
import type { MediaRef } from '@/types/nostr'
import { t } from '@/lib/i18n'

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

function CategoryField({
  value,
  onChange,
}: {
  value: ArticleDraft['category']
  onChange: (value: import('@/types/nostr').ArticleCategory | undefined) => void
}): React.ReactElement {
  return (
    <CategorySelect
      id="category"
      label={t('article.editor.category')}
      {...(value ? { value } : {})}
      onChange={onChange}
      required
      helpText={t('article.editor.category.help')}
    />
  )
}

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>
  )
}

function buildCategoryChangeHandler(
  draft: ArticleDraft,
  onDraftChange: (draft: ArticleDraft) => void
): (value: ArticleCategory | undefined) => void {
  return (value) => {
    if (value === 'science-fiction' || value === 'scientific-research' || value === undefined) {
      const nextDraft: ArticleDraft = { ...draft }
      if (value) {
        nextDraft.category = value
      } else {
        delete (nextDraft as { category?: ArticleDraft['category'] }).category
      }
      onDraftChange(nextDraft)
    }
  }
}

const ArticleFieldsLeft = ({
  draft,
  onDraftChange,
  seriesOptions,
  onSelectSeries,
}: {
  draft: ArticleDraft
  onDraftChange: (draft: ArticleDraft) => void
  seriesOptions?: { id: string; title: string }[] | undefined
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
}): React.ReactElement => (
  <div className="space-y-4">
    <CategoryField
      value={draft.category}
      onChange={buildCategoryChangeHandler(draft, onDraftChange)}
    />
    {seriesOptions && (
      <SeriesSelect
        draft={draft}
        onDraftChange={onDraftChange}
        seriesOptions={seriesOptions}
        onSelectSeries={onSelectSeries}
      />
    )}
    <ArticleTitleField draft={draft} onDraftChange={onDraftChange} />
    <ArticlePreviewField draft={draft} onDraftChange={onDraftChange} />
  </div>
)

function ArticleTitleField({ draft, onDraftChange }: { draft: ArticleDraft; onDraftChange: (draft: ArticleDraft) => void }): React.ReactElement {
  return (
    <ArticleField
      id="title"
      label={t('article.title')}
      value={draft.title}
      onChange={(value) => onDraftChange({ ...draft, title: value as string })}
      required
      placeholder={t('article.editor.title.placeholder')}
    />
  )
}

function ArticlePreviewField({
  draft,
  onDraftChange,
}: {
  draft: ArticleDraft
  onDraftChange: (draft: ArticleDraft) => void
}): React.ReactElement {
  return (
    <ArticleField
      id="preview"
      label={t('article.editor.preview.label')}
      value={draft.preview}
      onChange={(value) => onDraftChange({ ...draft, preview: value as string })}
      required
      type="textarea"
      rows={4}
      placeholder={t('article.editor.preview.placeholder')}
      helpText={t('article.editor.preview.help')}
    />
  )
}

function SeriesSelect({
  draft,
  onDraftChange,
  seriesOptions,
  onSelectSeries,
}: {
  draft: ArticleDraft
  onDraftChange: (draft: ArticleDraft) => void
  seriesOptions: { id: string; title: string }[]
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
}): React.ReactElement {
  const handleChange = buildSeriesChangeHandler(draft, onDraftChange, onSelectSeries)

  return (
    <div>
      <label htmlFor="series" className="block text-sm font-medium text-gray-700">
        {t('article.editor.series.label')}
      </label>
      <select
        id="series"
        className="mt-1 block w-full border-gray-300 rounded-md shadow-sm"
        value={draft.seriesId ?? ''}
        onChange={handleChange}
      >
        <option value="">{t('article.editor.series.none')}</option>
        {seriesOptions.map((s) => (
          <option key={s.id} value={s.id}>
            {s.title}
          </option>
        ))}
      </select>
    </div>
  )
}

function buildSeriesChangeHandler(
  draft: ArticleDraft,
  onDraftChange: (draft: ArticleDraft) => void,
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
): (e: React.ChangeEvent<HTMLSelectElement>) => void {
  return (e: React.ChangeEvent<HTMLSelectElement>): void => {
    const value = e.target.value || undefined
    const nextDraft = { ...draft }
    if (value) {
      nextDraft.seriesId = value
    } else {
      delete (nextDraft as { seriesId?: string }).seriesId
    }
    onDraftChange(nextDraft)
    onSelectSeries?.(value)
  }
}

const ArticleFieldsRight = ({
  draft,
  onDraftChange,
}: {
  draft: ArticleDraft
  onDraftChange: (draft: ArticleDraft) => void
}): React.ReactElement => {
  // Use two-column editor with pages for series publications
  const useTwoColumns = draft.seriesId !== undefined

  return (
    <div className="space-y-4">
      <div className="space-y-2">
        <div className="text-sm font-semibold text-gray-800">{t('article.editor.content.label')}</div>
        {useTwoColumns ? (
          <MarkdownEditorTwoColumns
            value={draft.content}
            onChange={(value) => onDraftChange({ ...draft, content: value })}
            pages={draft.pages}
            onPagesChange={(pages) => onDraftChange({ ...draft, pages })}
            onMediaAdd={(media: MediaRef) => {
              const nextMedia = [...(draft.media ?? []), media]
              onDraftChange({ ...draft, media: nextMedia })
            }}
            onBannerChange={(url: string) => {
              onDraftChange({ ...draft, bannerUrl: url })
            }}
          />
        ) : (
          <MarkdownEditor
            value={draft.content}
            onChange={(value) => onDraftChange({ ...draft, content: value })}
            onMediaAdd={(media: MediaRef) => {
              const nextMedia = [...(draft.media ?? []), media]
              onDraftChange({ ...draft, media: nextMedia })
            }}
            onBannerChange={(url: string) => {
              onDraftChange({ ...draft, bannerUrl: url })
            }}
          />
        )}
        <p className="text-xs text-gray-500">
          {t('article.editor.content.help')}
        </p>
      </div>
      <ArticleField
        id="zapAmount"
        label={t('article.editor.sponsoring.label')}
        value={draft.zapAmount}
        onChange={(value) => onDraftChange({ ...draft, zapAmount: value as number })}
        required
        type="number"
        min={1}
        helpText={t('article.editor.sponsoring.help')}
      />
    </div>
  )
}

export function ArticleEditorForm({
  draft,
  onDraftChange,
  onSubmit,
  loading,
  error,
  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} {...(onCancel ? { onCancel } : {})} />
    </form>
  )
}
