import { useRouter } from 'next/router'
import Head from 'next/head'
import { useEffect, useState } from 'react'
import { getSeriesById } from '@/lib/seriesQueries'
import { getSeriesAggregates } from '@/lib/seriesAggregation'
import { getArticlesBySeries } from '@/lib/articleQueries'
import type { Series, Article } from '@/types/nostr'
import { SeriesStats } from '@/components/SeriesStats'
import { ArticleCard } from '@/components/ArticleCard'
import Image from 'next/image'
import { ArticleReviews } from '@/components/ArticleReviews'

function SeriesHeader({ series }: { series: Series }) {
  return (
    <div className="space-y-3">
      {series.coverUrl && (
        <div className="relative w-full h-48">
          <Image
            src={series.coverUrl}
            alt={series.title}
            fill
            sizes="(max-width: 768px) 100vw, 50vw"
            className="object-cover rounded"
          />
        </div>
      )}
      <h1 className="text-3xl font-bold">{series.title}</h1>
      <p className="text-gray-700">{series.description}</p>
      <p className="text-sm text-gray-500">Catégorie : {series.category === 'science-fiction' ? 'Science-fiction' : 'Recherche scientifique'}</p>
    </div>
  )
}

export default function SeriesPage() {
  const router = useRouter()
  const { id } = router.query
  const seriesId = typeof id === 'string' ? id : ''
  const { series, articles, aggregates, loading, error } = useSeriesPageData(seriesId)

  if (!seriesId) {
    return null
  }
  return (
    <>
      <Head>
        <title>Série - zapwall4Science</title>
      </Head>
      <main className="min-h-screen bg-gray-50">
        <div className="max-w-4xl mx-auto px-4 py-8 space-y-6">
          {loading && <p className="text-sm text-gray-600">Chargement...</p>}
          {error && <p className="text-sm text-red-600">{error}</p>}
          {series && (
            <>
              <SeriesHeader series={series} />
              <SeriesStats
                sponsoring={aggregates?.sponsoring ?? 0}
                purchases={aggregates?.purchases ?? 0}
                reviewTips={aggregates?.reviewTips ?? 0}
              />
              <SeriesArticles articles={articles} />
            </>
          )}
        </div>
      </main>
    </>
  )
}

function SeriesArticles({ articles }: { articles: Article[] }) {
  if (articles.length === 0) {
    return <p className="text-sm text-gray-600">Aucun article pour cette série.</p>
  }
  return (
    <div className="space-y-4">
      <h2 className="text-2xl font-semibold">Articles de la série</h2>
      <div className="space-y-4">
        {articles.map((a) => (
          <div key={a.id} className="space-y-2">
            <ArticleCard article={a} onUnlock={() => {}} />
            <ArticleReviews articleId={a.id} authorPubkey={a.pubkey} />
          </div>
        ))}
      </div>
    </div>
  )
}

function useSeriesPageData(seriesId: string) {
  const [series, setSeries] = useState<Series | null>(null)
  const [articles, setArticles] = useState<Article[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [aggregates, setAggregates] = useState<{ sponsoring: number; purchases: number; reviewTips: number } | null>(null)

  useEffect(() => {
    if (!seriesId) {
      return
    }
    const load = async () => {
      setLoading(true)
      setError(null)
      try {
        const s = await getSeriesById(seriesId)
        if (!s) {
          setError('Série introuvable')
          setLoading(false)
          return
        }
        setSeries(s)
        const [agg, seriesArticles] = await Promise.all([
          getSeriesAggregates({ authorPubkey: s.pubkey, seriesId: s.id }),
          getArticlesBySeries(s.id),
        ])
        setAggregates(agg)
        setArticles(seriesArticles)
      } catch (e) {
        setError(e instanceof Error ? e.message : 'Erreur lors du chargement de la série')
      } finally {
        setLoading(false)
      }
    }
    void load()
  }, [seriesId])

  return { series, articles, aggregates, loading, error }
}
