import { useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
import { ChevronRight } from '../../lib/icons'

interface Keyword {
  id: number
  name: string
}

interface Props {
  keywords: Keyword[] | null | undefined
  /** Plain-text "Production" section pulled from Wikipedia. Optional. */
  wikiProduction?: { extract: string; title: string } | null | undefined
}

/**
 * Trivia block combining TMDB keywords (always present, lots of them)
 * with the Wikipedia "Production" section (richer, sometimes long).
 *
 * The wiki extract collapses to the first 3 paragraphs by default to keep
 * the page calm; a "Read more" toggle reveals the rest.
 */
export default function ProductionTrivia({ keywords, wikiProduction }: Props) {
  const [expanded, setExpanded] = useState(false)
  const hasKeywords = (keywords?.length ?? 0) > 0
  const hasWiki = !!wikiProduction?.extract

  if (!hasKeywords && !hasWiki) return null

  const fullParagraphs = (wikiProduction?.extract || '')
    .split(/\n{2,}/)
    .map(p => p.trim())
    .filter(p => p.length > 30)
  const previewParagraphs = fullParagraphs.slice(0, 3)
  const hasMore = fullParagraphs.length > previewParagraphs.length
  const shown = expanded ? fullParagraphs : previewParagraphs

  return (
    <div className="space-y-5">
      {hasWiki && shown.length > 0 && (
        <div>
          <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-2.5">
            Production
          </p>
          <div className="space-y-3 text-[13.5px] text-text-2 leading-relaxed">
            {shown.map((p, i) => (
              <motion.p
                key={i}
                initial={{ opacity: 0, y: 4 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ duration: 0.3, delay: Math.min(i * 0.05, 0.3) }}
              >
                {p}
              </motion.p>
            ))}
          </div>
          {hasMore && (
            <button
              onClick={() => setExpanded(v => !v)}
              className="mt-3 inline-flex items-center gap-1 text-[11.5px] text-accent hover:text-accent-hover tracking-tight focus-ring rounded"
            >
              {expanded ? 'Show less' : 'Read more'}
              <motion.span animate={{ rotate: expanded ? 90 : 0 }} transition={{ duration: 0.2 }}>
                <ChevronRight size={11} />
              </motion.span>
            </button>
          )}
          <AnimatePresence>
            {wikiProduction?.title && (
              <motion.p
                key="src"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="mt-3 text-[10.5px] text-text-5 tracking-tight"
              >
                Source: Wikipedia, "{wikiProduction.title}"
              </motion.p>
            )}
          </AnimatePresence>
        </div>
      )}
    </div>
  )
}
