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 { t } from '@/lib/i18n'
import Image from 'next/image'
import { ArticleReviews } from '@/components/ArticleReviews'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import Link from 'next/link'

function SeriesHeader({ series }: { series: Series }): React.ReactElement {
  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">
          {t('category.science-fiction')}: {series.category === 'science-fiction' ? t('category.science-fiction') : t('category.scientific-research')}
        </p>
      {series.preview && (
        <div className="mt-4 p-4 bg-gray-50 rounded-lg">
          <p className="text-gray-700 whitespace-pre-wrap">{series.preview}</p>
        </div>
      )}
    </div>
  )
}

export default function SeriesPage(): React.ReactElement | null {
  const router = useRouter()
  const { id } = router.query
  const seriesId = getSeriesIdFromQuery(id)
  const data = useSeriesPageData(seriesId ?? '')

  if (!seriesId) {
    return null
  }
  return <SeriesPageView series={data.series} articles={data.articles} aggregates={data.aggregates} loading={data.loading} error={data.error} />
}

function getSeriesIdFromQuery(id: unknown): string | null {
  return typeof id === 'string' && id.trim() ? id : null
}

function SeriesPageView({
  series,
  articles,
  aggregates,
  loading,
  error,
}: {
  series: Series | null
  articles: Article[]
  aggregates: { sponsoring: number; purchases: number; reviewTips: number } | null
  loading: boolean
  error: string | null
}): React.ReactElement {
  return (
    <>
      <Head>
        <title>Série - zapwall.fr</title>
      </Head>
      <main className="min-h-screen bg-gray-50">
        <div className="w-full px-4 py-8 space-y-6">
          <SeriesPageStatus loading={loading} error={error} />
          {series ? <SeriesPageContent series={series} articles={articles} aggregates={aggregates} /> : null}
        </div>
      </main>
    </>
  )
}

function SeriesPageStatus({ loading, error }: { loading: boolean; error: string | null }): React.ReactElement | null {
  if (loading) {
    return <p className="text-sm text-gray-600">{t('common.loading')}</p>
  }
  if (error) {
    return <p className="text-sm text-red-600">{error}</p>
  }
  return null
}

function SeriesPageContent({
  series,
  articles,
  aggregates,
}: {
  series: Series
  articles: Article[]
  aggregates: { sponsoring: number; purchases: number; reviewTips: number } | null
}): React.ReactElement {
  return (
    <>
      <SeriesHeader series={series} />
      <SeriesActions series={series} />
      <SeriesStats
        sponsoring={aggregates?.sponsoring ?? 0}
        purchases={aggregates?.purchases ?? 0}
        reviewTips={aggregates?.reviewTips ?? 0}
      />
      <SeriesPublications articles={articles} />
    </>
  )
}

function SeriesActions({ series }: { series: Series }): React.ReactElement | null {
  const { pubkey } = useNostrAuth()

  // Only show "Create Publication" button if user is the author
  if (!pubkey || pubkey !== series.pubkey) {
    return null
  }

  return (
    <div className="mb-4">
      <Link
        href={`/series/${series.id}/publish`}
        className="inline-block px-4 py-2 bg-neon-cyan text-cyber-darker rounded-lg hover:bg-neon-cyan/90 transition-colors font-medium"
      >
        {t('series.createPublication')}
      </Link>
    </div>
  )
}

function SeriesPublications({ articles }: { articles: Article[] }): React.ReactElement {
  if (articles.length === 0) {
    return <p className="text-sm text-gray-600">Aucune publication pour cette série.</p>
  }
  return (
    <div className="space-y-4">
      <h2 className="text-2xl font-semibold">{t('series.publications')}</h2>
      <div className="space-y-4">
        {articles.map((a) => (
          <div key={a.id} className="space-y-2">
            <ArticleCard article={a} onUnlock={() => {}} />
            <ArticleReviews article={a} authorPubkey={a.pubkey} />
          </div>
        ))}
      </div>
    </div>
  )
}

type SeriesAggregates = { sponsoring: number; purchases: number; reviewTips: number }

type SeriesPageData = {
  series: Series | null
  articles: Article[]
  aggregates: SeriesAggregates | null
  loading: boolean
  error: string | null
}

function useSeriesPageData(seriesId: string): SeriesPageData {
  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<SeriesAggregates | null>(null)

  useEffect(() => {
    if (!seriesId) {
      return
    }
    const load = async (): Promise<void> => {
      setLoading(true)
      setError(null)
      try {
        // First try cache (should be very fast)
        const s = await getSeriesById(seriesId, 2000)
        if (!s) {
          setError('Série introuvable')
          setLoading(false)
          return
        }
        setSeries(s)
        // Load aggregates and articles in parallel
        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 }
}
