import { useRouter } from 'next/router'
import Head from 'next/head'
import { useEffect, useState, useCallback } from 'react'
import { fetchAuthorByHashId } from '@/lib/authorQueries'
import { getSeriesByAuthor } from '@/lib/seriesQueries'
import { getAuthorSponsoring } from '@/lib/sponsoring'
import { nostrService } from '@/lib/nostr'
import type { AuthorPresentationArticle, Series } from '@/types/nostr'
import { PageHeader } from '@/components/PageHeader'
import { Footer } from '@/components/Footer'
import { t } from '@/lib/i18n'
import Link from 'next/link'
import { SeriesCard } from '@/components/SeriesCard'
import Image from 'next/image'
import { CreateSeriesModal } from '@/components/CreateSeriesModal'
import { useNostrAuth } from '@/hooks/useNostrAuth'
import { parseObjectUrl } from '@/lib/urlGenerator'
import { SponsoringForm } from '@/components/SponsoringForm'

function AuthorPageHeader({ presentation }: { presentation: AuthorPresentationArticle | null }): React.ReactElement | null {
  if (!presentation) {
    return null
  }

  // Extract author name from title (format: "Présentation de <name>")
  const trimmed = presentation.title.replace(/^Présentation de /, '').trim()
  const authorName = trimmed || presentation.title

  return (
    <div className="space-y-4 mb-8">
      <div className="flex items-start gap-6">
        {presentation.bannerUrl && (
          <div className="relative w-32 h-32 rounded-lg overflow-hidden border border-neon-cyan/20 flex-shrink-0">
            <Image
              src={presentation.bannerUrl}
              alt={t('author.profilePicture')}
              fill
              className="object-cover"
            />
          </div>
        )}
        <div className="flex-1 space-y-4">
          <div>
            <h1 className="text-3xl font-bold text-neon-cyan mb-2">
              {authorName}
            </h1>
            <p className="text-xs text-cyber-accent/60 italic mb-4">
              {t('author.profileNote')}
            </p>
          </div>
          {presentation.description && (
            <div className="space-y-2">
              <h2 className="text-lg font-semibold text-neon-cyan">
                {t('presentation.field.presentation')}
              </h2>
              <div className="prose prose-invert max-w-none">
                <p className="text-cyber-accent whitespace-pre-wrap">{presentation.description}</p>
              </div>
            </div>
          )}
          {presentation.contentDescription && (
            <div className="space-y-2">
              <h2 className="text-lg font-semibold text-neon-cyan">
                {t('presentation.field.contentDescription')}
              </h2>
              <div className="prose prose-invert max-w-none">
                <p className="text-cyber-accent whitespace-pre-wrap">{presentation.contentDescription}</p>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

function SponsoringSummary({ totalSponsoring, author, onSponsor }: { totalSponsoring: number; author: AuthorPresentationArticle | null; onSponsor: () => void }): React.ReactElement {
  const totalBTC = totalSponsoring / 100_000_000
  const [showForm, setShowForm] = useState(false)

  return (
    <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6 mb-8">
      <div className="flex items-center justify-between mb-4">
        <h2 className="text-xl font-semibold text-neon-cyan">{t('author.sponsoring')}</h2>
        {author && (
          <button
            onClick={() => {
              setShowForm(true)
            }}
            className="px-4 py-2 bg-neon-green/20 hover:bg-neon-green/30 text-neon-green rounded-lg font-medium transition-all border border-neon-green/50"
          >
            {t('sponsoring.form.submit')}
          </button>
        )}
      </div>
      <div className="space-y-2">
        <p className="text-cyber-accent">
          {t('author.sponsoring.total', { amount: totalBTC.toFixed(6) })}
        </p>
        <p className="text-cyber-accent">
          {t('author.sponsoring.sats', { amount: totalSponsoring.toLocaleString() })}
        </p>
      </div>
      {showForm && author && (
        <div className="mt-4">
          <SponsoringForm
            author={author}
            onSuccess={() => {
              setShowForm(false)
              onSponsor()
            }}
            onCancel={() => {
              setShowForm(false)
            }}
          />
        </div>
      )}
    </div>
  )
}

function SeriesList({ series, authorPubkey, onSeriesCreated }: { series: Series[]; authorPubkey: string; onSeriesCreated: () => void }): React.ReactElement {
  const { pubkey, isUnlocked } = useNostrAuth()
  const [showCreateModal, setShowCreateModal] = useState(false)
  const isAuthor = pubkey === authorPubkey && isUnlocked

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <h2 className="text-2xl font-semibold text-neon-cyan">{t('series.title')}</h2>
        {isAuthor && (
          <button
            type="button"
            onClick={() => setShowCreateModal(true)}
            className="px-4 py-2 bg-neon-cyan/20 hover:bg-neon-cyan/30 text-neon-cyan rounded-lg font-medium transition-all border border-neon-cyan/50 hover:shadow-glow-cyan"
          >
            {t('series.create.button')}
          </button>
        )}
      </div>
      {series.length === 0 ? (
        <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6">
          <p className="text-cyber-accent">{t('series.empty')}</p>
        </div>
      ) : (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {series.map((s) => (
            <Link key={s.id} href={`/series/${s.id}`}>
              <SeriesCard series={s} onSelect={() => {}} />
            </Link>
          ))}
        </div>
      )}
      <CreateSeriesModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onSuccess={onSeriesCreated}
        authorPubkey={authorPubkey}
      />
    </div>
  )
}

async function loadAuthorData(hashId: string): Promise<{ pres: AuthorPresentationArticle | null; seriesList: Series[]; sponsoring: number }> {
  const pool = nostrService.getPool()
  if (!pool) {
    throw new Error('Pool not initialized')
  }

  const pres = await fetchAuthorByHashId(pool, hashId)
  if (!pres) {
    return { pres: null, seriesList: [], sponsoring: 0 }
  }

  const [seriesList, sponsoring] = await Promise.all([
    getSeriesByAuthor(pres.pubkey),
    getAuthorSponsoring(pres.pubkey),
  ])

  return { pres, seriesList, sponsoring }
}

function useAuthorData(hashIdOrPubkey: string): {
  presentation: AuthorPresentationArticle | null
  series: Series[]
  totalSponsoring: number
  loading: boolean
  error: string | null
  reload: () => Promise<void>
} {
  const [presentation, setPresentation] = useState<AuthorPresentationArticle | null>(null)
  const [series, setSeries] = useState<Series[]>([])
  const [totalSponsoring, setTotalSponsoring] = useState<number>(0)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)

  const reload = useCallback(async (): Promise<void> => {
    if (!hashIdOrPubkey) {
      return
    }

    setLoading(true)
    setError(null)

    try {
      const { pres, seriesList, sponsoring } = await loadAuthorData(hashIdOrPubkey)
      setPresentation(pres)
      setSeries(seriesList)
      setTotalSponsoring(sponsoring)
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Erreur lors du chargement')
    } finally {
      setLoading(false)
    }
  }, [hashIdOrPubkey])

  useEffect(() => {
    void reload()
  }, [hashIdOrPubkey, reload])

  return { presentation, series, totalSponsoring, loading, error, reload }
}

function AuthorPageContent({
  presentation,
  series,
  totalSponsoring,
  authorPubkey,
  loading,
  error,
  onSeriesCreated,
}: {
  presentation: AuthorPresentationArticle | null
  series: Series[]
  totalSponsoring: number
  authorPubkey: string
  loading: boolean
  error: string | null
  onSeriesCreated: () => void
}): React.ReactElement {
  if (loading) {
    return <p className="text-cyber-accent">{t('common.loading')}</p>
  }

  if (error) {
    return <p className="text-red-400">{error}</p>
  }

  if (presentation) {
    return (
      <>
        <AuthorPageHeader presentation={presentation} />
        <SponsoringSummary
          totalSponsoring={totalSponsoring}
          author={presentation}
          onSponsor={onSeriesCreated}
        />
        <SeriesList series={series} authorPubkey={authorPubkey} onSeriesCreated={onSeriesCreated} />
      </>
    )
  }

  return (
    <div className="bg-cyber-dark/50 border border-neon-cyan/20 rounded-lg p-6">
      <p className="text-cyber-accent">{t('author.notFound')}</p>
    </div>
  )
}

export default function AuthorPage(): React.ReactElement {
  const router = useRouter()
  const { pubkey } = router.query

  // Parse the URL parameter - it can be either:
  // 1. Old format: /author/<pubkey> (for backward compatibility)
  // 2. New format: /author/<hash>_<index>_<version> (standard format)
  let hashIdOrPubkey: string | null = null

  if (typeof pubkey === 'string') {
    // Try to parse as new format first (hash_index_version)
    const urlMatch = pubkey.match(/^([a-f0-9]+)_(\d+)_(\d+)$/i)
    if (urlMatch?.[1]) {
      // Extract hash ID from the format hash_index_version
      hashIdOrPubkey = urlMatch[1]
    } else {
      // Try to parse as full URL format
      const parsedUrl = parseObjectUrl(`https://zapwall.fr/author/${pubkey}`)
      if (parsedUrl.objectType === 'author' && parsedUrl.idHash) {
        hashIdOrPubkey = parsedUrl.idHash
      } else {
        // Legacy: treat as pubkey for backward compatibility (64 hex chars)
        hashIdOrPubkey = pubkey
      }
    }
  }

  const { presentation, series, totalSponsoring, loading, error, reload } = useAuthorData(hashIdOrPubkey ?? '')
  const onSeriesCreated = (): void => {
    void reload()
  }

  if (!hashIdOrPubkey) {
    return <div />
  }

  // Get the actual pubkey from presentation
  const actualAuthorPubkey = presentation?.pubkey ?? ''

  return (
    <>
      <Head>
        <title>{t('author.title')} - {t('home.title')}</title>
        <meta name="description" content={t('author.presentation')} />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
      </Head>
      <main className="min-h-screen bg-cyber-darker">
        <PageHeader />
        <div className="w-full px-4 py-8">
          <AuthorPageContent
            presentation={presentation}
            series={series}
            totalSponsoring={totalSponsoring}
            authorPubkey={actualAuthorPubkey}
            loading={loading}
            error={error}
            onSeriesCreated={onSeriesCreated}
          />
        </div>
        <Footer />
      </main>
    </>
  )
}
