import { ArticleCard } from './ArticleCard'
import { Button, ErrorState } from './ui'
import type { Article } from '@/types/nostr'
import { memo } from 'react'
import Link from 'next/link'
import { t } from '@/lib/i18n'

interface UserArticlesViewProps {
  articles: Article[]
  loading: boolean
  error: string | null
  showEmptyMessage?: boolean
  unlockedArticles: Set<string>
  onUnlock: (article: Article) => void
  onEdit: (article: Article) => void
  onDelete: (article: Article) => void
  editingArticleId: string | null
  currentPubkey: string | null
  pendingDeleteId: string | null
  requestDelete: (articleId: string) => void
  onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
}

const ArticlesLoading = (): React.ReactElement => (
  <div className="text-center py-12">
    <p className="text-gray-500">{t('common.loading.articles')}</p>
  </div>
)

const ArticlesError = ({ message }: { message: string }): React.ReactElement => (
  <div className="mb-4">
    <ErrorState message={message} />
  </div>
)

const EmptyState = ({ show }: { show: boolean }): React.ReactElement | null =>
  (show ? (
    <div className="text-center py-12">
      <p className="text-gray-500">{t('common.empty.articles')}</p>
    </div>
  ) : null)

function ArticleActions({
  article,
  onEdit,
  onDelete,
  editingArticleId,
  pendingDeleteId,
  requestDelete,
}: {
  article: Article
  onEdit: (article: Article) => void
  onDelete: (article: Article) => void
  editingArticleId: string | null
  pendingDeleteId: string | null
  requestDelete: (articleId: string) => void
}): React.ReactElement {
  return (
    <div className="flex gap-2">
      <Button
        variant="primary"
        size="small"
        onClick={() => onEdit(article)}
        disabled={editingArticleId !== null && editingArticleId !== article.id}
      >
        {t('common.edit')}
      </Button>
      <Button
        variant="danger"
        size="small"
        onClick={() => (pendingDeleteId === article.id ? onDelete(article) : requestDelete(article.id))}
      >
        {pendingDeleteId === article.id ? t('common.confirmDelete') : t('common.delete')}
      </Button>
    </div>
  )
}

function ArticleRow(
  props: Omit<UserArticlesViewProps, 'articles' | 'loading' | 'error' | 'showEmptyMessage'> & {
    article: Article
    onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
  }
): React.ReactElement {
  const content = buildArticleContent(props)
  return <div className="space-y-3">{content}</div>
}

function buildArticleContent(
  props: Omit<UserArticlesViewProps, 'articles' | 'loading' | 'error' | 'showEmptyMessage'> & {
    article: Article
    onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
  }
): React.ReactElement[] {
  const parts = [buildArticleCard(props), buildSeriesLink(props), buildActions(props)].filter(Boolean)
  return parts as React.ReactElement[]
}

function buildArticleCard(
  props: Omit<UserArticlesViewProps, 'articles' | 'loading' | 'error' | 'showEmptyMessage'> & { article: Article }
): React.ReactElement {
  const { article, unlockedArticles, onUnlock } = props
  return (
    <ArticleCard
      key="card"
      article={{ ...article, paid: unlockedArticles.has(article.id) || article.paid }}
      onUnlock={onUnlock}
    />
  )
}

function buildSeriesLink(
  props: Omit<UserArticlesViewProps, 'articles' | 'loading' | 'error' | 'showEmptyMessage'> & {
    article: Article
    onSelectSeries?: ((seriesId: string | undefined) => void) | undefined
  }
): React.ReactElement | null {
  const { article, onSelectSeries } = props
  if (!article.seriesId) {
    return null
  }
  return (
    <div key="series" className="text-xs text-blue-700 flex gap-2 items-center">
      <span>Série :</span>
      <Link href={`/series/${article.seriesId}`} className="underline">
        Ouvrir
      </Link>
      {onSelectSeries && (
        <Button type="button" variant="ghost" size="small" onClick={() => onSelectSeries(article.seriesId)} className="underline p-0 h-auto">
          Filtrer
        </Button>
      )}
    </div>
  )
}

function buildActions(
  props: Omit<UserArticlesViewProps, 'articles' | 'loading' | 'error' | 'showEmptyMessage'> & { article: Article }
): React.ReactElement | null {
  const { article, currentPubkey, onEdit, onDelete, editingArticleId, pendingDeleteId, requestDelete } = props
  if (currentPubkey !== article.pubkey) {
    return null
  }
  return (
    <ArticleActions
      key="actions"
      article={article}
      onEdit={onEdit}
      onDelete={onDelete}
      editingArticleId={editingArticleId}
      pendingDeleteId={pendingDeleteId}
      requestDelete={requestDelete}
    />
  )
}

function UserArticlesViewComponent(props: UserArticlesViewProps): React.ReactElement {
  if (props.loading) {
    return <ArticlesLoading />
  }
  if (props.error) {
    return <ArticlesError message={props.error} />
  }
  if ((props.showEmptyMessage ?? true) && props.articles.length === 0) {
    return <EmptyState show />
  }
  return renderArticles(props)
}

function renderArticles({
  articles,
  unlockedArticles,
  onUnlock,
  onEdit,
  onDelete,
  editingArticleId,
  currentPubkey,
  pendingDeleteId,
  requestDelete,
  onSelectSeries,
}: UserArticlesViewProps): React.ReactElement {
  return (
    <div className="space-y-6">
      {articles.map((article) => (
        <ArticleRow
          key={article.id}
          article={article}
          unlockedArticles={unlockedArticles}
          onUnlock={onUnlock}
          onEdit={onEdit}
          onDelete={onDelete}
          editingArticleId={editingArticleId}
          currentPubkey={currentPubkey}
          pendingDeleteId={pendingDeleteId}
          requestDelete={requestDelete}
          onSelectSeries={onSelectSeries}
        />
      ))}
    </div>
  )
}

export const UserArticlesView = memo(UserArticlesViewComponent)
