'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { useVisitor } from '@/context/VisitorContext'
import { tPlain } from '@/lib/i18n'
import type { SectionDTO, OrderedTranslationAndResourceDTO } from '@/lib/api/types'
import AppBar from '@/components/ui/AppBar'

interface Props {
  section: SectionDTO
  slug: string
  configId: string
  languages: string[]
}

export default function PdfSection({ section, slug, configId, languages }: Props) {
  const { language, setAvailableLanguages } = useVisitor()
  const router = useRouter()

  useEffect(() => { setAvailableLanguages(languages) }, [languages])

  const pdfs = [...(section.pdf?.pdfs ?? [])].sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
  const [selectedIndex, setSelectedIndex] = useState(0)

  function getPdfUrl(pdf: OrderedTranslationAndResourceDTO): string | undefined {
    const translations = pdf.translationAndResourceDTOs ?? []
    return (
      translations.find((t) => t.language === language)?.resource?.url ??
      translations[0]?.resource?.url
    )
  }

  const currentUrl = pdfs.length > 0 ? getPdfUrl(pdfs[selectedIndex]) : undefined

  return (
    <div style={{ position: 'fixed', inset: 0, display: 'flex', flexDirection: 'column', background: 'var(--color-background)' }}>
      <AppBar title={tPlain(section.title, language)} onBack={() => router.back()} />

      {pdfs.length > 1 && (
        <div className="flex gap-2 px-4 py-2 overflow-x-auto shrink-0">
          {pdfs.map((pdf, i) => (
            <button
              key={i}
              onClick={() => setSelectedIndex(i)}
              className="shrink-0 px-3 py-1.5 rounded-full text-xs font-medium"
              style={{
                background: i === selectedIndex ? 'var(--color-primary)' : 'var(--color-surface)',
                color: i === selectedIndex ? 'var(--color-on-primary)' : 'var(--color-text)',
              }}
            >
              PDF {i + 1}
            </button>
          ))}
        </div>
      )}

      <div style={{ flex: 1, borderRadius: '20px 20px 0 0', overflow: 'hidden' }}>
        {!currentUrl ? (
          <div className="h-full flex items-center justify-center text-sm p-8 text-center" style={{ color: 'var(--color-text-muted)' }}>
            Aucun PDF à afficher
          </div>
        ) : (
          <iframe
            src={currentUrl}
            title={tPlain(section.title, language)}
            style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
          />
        )}
      </div>
    </div>
  )
}
