import type { ArticleFilters } from '@/components/ArticleFilters'
import type { Article } from '@/types/nostr'
import { ArticlesSummary } from '@/components/ProfileArticlesSummary'
import { UserArticles } from '@/components/UserArticles'
import { ProfileArticlesHeader } from '@/components/ProfileArticlesHeader'
import { ProfileSeriesBlock } from '@/components/ProfileSeriesBlock'

export interface ProfileArticlesSectionProps {
  searchQuery: string
  setSearchQuery: (value: string) => void
  filters: ArticleFilters
  setFilters: (value: ArticleFilters) => void
  articles: Article[]
  allArticles: Article[]
  loading: boolean
  error: string | null
  loadArticleContent: (id: string, pubkey: string) => Promise<Article | null>
  currentPubkey: string
  selectedSeriesId?: string | undefined
  onSelectSeries: (seriesId: string | undefined) => void
  articleFiltersVisible: boolean
}

export function ProfileArticlesSection(props: ProfileArticlesSectionProps) {
  const filtered = filterArticlesBySeries(props.articles, props.allArticles, props.selectedSeriesId)

  return (
    <>
      <ProfileArticlesHeader
        searchQuery={props.searchQuery}
        setSearchQuery={props.setSearchQuery}
        filters={props.filters}
        setFilters={props.setFilters}
        allArticles={props.allArticles}
        articleFiltersVisible={props.articleFiltersVisible}
      />
      <ArticlesSummary visibleCount={filtered.articles.length} total={filtered.all.length} />
      <ProfileSeriesBlock
        currentPubkey={props.currentPubkey}
        onSelectSeries={props.onSelectSeries}
        {...(props.selectedSeriesId ? { selectedSeriesId: props.selectedSeriesId } : {})}
      />
      <UserArticles
        articles={filtered.articles}
        loading={props.loading}
        error={props.error}
        onLoadContent={props.loadArticleContent}
        showEmptyMessage
        currentPubkey={props.currentPubkey}
        onSelectSeries={props.onSelectSeries}
      />
    </>
  )
}

function filterArticlesBySeries(
  articles: Article[],
  allArticles: Article[],
  selectedSeriesId?: string | undefined
): { articles: Article[]; all: Article[] } {
  if (!selectedSeriesId) {
    return { articles, all: allArticles }
  }
  return {
    articles: articles.filter((a) => a.seriesId === selectedSeriesId),
    all: allArticles.filter((a) => a.seriesId === selectedSeriesId),
  }
}
