import React from 'react'
import type { Article } from '@/types/nostr'
import { Button, Card, Input } from './ui'
import { t } from '@/lib/i18n'
import { AuthorFilter } from './AuthorFilter'

export type SortOption = 'newest' | 'oldest'

export interface ArticleFilters {
  authorPubkey: string | null
  sortBy: SortOption
  category: 'science-fiction' | 'scientific-research' | 'all' | null
}

interface ArticleFiltersProps {
  filters: ArticleFilters
  onFiltersChange: (filters: ArticleFilters) => void
  articles: Article[]
}

interface FiltersData {
  authors: string[]
}

function useFiltersData(articles: Article[]): FiltersData {
  const authorArticleCount = new Map<string, number>()
  articles.forEach((article) => {
    if (!article.isPresentation) {
      const count = authorArticleCount.get(article.pubkey) ?? 0
      authorArticleCount.set(article.pubkey, count + 1)
    }
  })
  const authors = Array.from(authorArticleCount.keys()).filter((pubkey) => {
    const count = authorArticleCount.get(pubkey) ?? 0
    return count > 0
  })
  return {
    authors,
  }
}

function FiltersGrid({
  data,
  filters,
  onFiltersChange,
}: {
  data: FiltersData
  filters: ArticleFilters
  onFiltersChange: (filters: ArticleFilters) => void
}): React.ReactElement {
  const update = (patch: Partial<ArticleFilters>): void => onFiltersChange({ ...filters, ...patch })

  return (
    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
      <AuthorFilter authors={data.authors} value={filters.authorPubkey} onChange={(value) => update({ authorPubkey: value })} />
      <SortFilter value={filters.sortBy} onChange={(value) => update({ sortBy: value })} />
    </div>
  )
}

function FiltersHeader({
  hasActiveFilters,
  onClear,
}: {
  hasActiveFilters: boolean
  onClear: () => void
}): React.ReactElement {
  return (
    <div className="flex justify-between items-center mb-4">
      <h3 className="text-lg font-semibold text-neon-cyan">{t('filters.sort')}</h3>
      {hasActiveFilters && (
        <Button onClick={onClear} variant="ghost" size="small" className="text-sm">
          {t('filters.clear')}
        </Button>
      )}
    </div>
  )
}


function SortFilter({
  value,
  onChange,
}: {
  value: SortOption
  onChange: (value: SortOption) => void
}): React.ReactElement {
  return (
    <div>
      <label htmlFor="sort" className="block text-sm font-medium text-cyber-accent mb-1">
        {t('filters.sort')}
      </label>
      <select
        id="sort"
        value={value}
        onChange={(e: React.ChangeEvent<HTMLSelectElement>) => onChange(e.target.value as SortOption)}
        className="block w-full border border-neon-cyan/30 rounded-lg focus:ring-2 focus:ring-neon-cyan focus:border-neon-cyan bg-cyber-dark text-cyber-accent hover:border-neon-cyan/50 transition-colors"
      >
        <option value="newest" className="bg-cyber-dark">{t('filters.sort.newest')}</option>
        <option value="oldest" className="bg-cyber-dark">{t('filters.sort.oldest')}</option>
      </select>
    </div>
  )
}

export function ArticleFiltersComponent({
  filters,
  onFiltersChange,
  articles,
}: ArticleFiltersProps): React.ReactElement {
  const data = useFiltersData(articles)

  const handleClearFilters = (): void => {
    onFiltersChange({
      authorPubkey: null,
      sortBy: 'newest',
      category: null,
    })
  }

  const hasActiveFilters =
    filters.authorPubkey !== null ||
    filters.sortBy !== 'newest' ||
    filters.category !== null

  return (
    <Card variant="default" className="mb-6 shadow-glow-cyan">
      <FiltersHeader hasActiveFilters={hasActiveFilters} onClear={handleClearFilters} />
      <FiltersGrid data={data} filters={filters} onFiltersChange={onFiltersChange} />
    </Card>
  )
}
