import { useState } from 'react'
import { motion } from 'framer-motion'
import { Star, ExternalLink } from '../../lib/icons'
import { getTmdbImageUrl, type TmdbReview } from '../../api/tmdb'
import { formatDate } from '../../lib/format'

interface Props {
  reviews?: TmdbReview[] | null
}

export default function ReviewsSection({ reviews }: Props) {
  const [expanded, setExpanded] = useState<Record<string, boolean>>({})
  const list = (reviews || []).slice(0, 4)
  if (!list.length) return null

  return (
    <div className="space-y-3">
      {list.map((r, i) => {
        const isOpen = expanded[r.id]
        const score = r.author_details?.rating
        const avatar = r.author_details?.avatar_path
        const isShortContent = (r.content?.length || 0) < 320

        return (
          <motion.article
            key={r.id}
            initial={{ opacity: 0, y: 8 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: Math.min(i * 0.05, 0.25) }}
            className="rounded-xl bg-elevated/40 border border-border p-4 hover:border-border-hover transition-colors"
          >
            <header className="flex items-center gap-3 mb-2">
              <div className="w-9 h-9 rounded-full overflow-hidden bg-higher ring-1 ring-border">
                {avatar ? (
                  <img
                    src={getTmdbImageUrl(normalizeAvatar(avatar), 'w92')}
                    alt={r.author}
                    className="w-full h-full object-cover"
                    loading="lazy"
                  />
                ) : (
                  <div className="w-full h-full grid place-items-center text-text-3 font-display font-semibold text-[13px]">
                    {(r.author || '?')[0].toUpperCase()}
                  </div>
                )}
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-[12.5px] text-text-1 font-medium truncate">{r.author}</p>
                <p className="text-[10.5px] text-text-4">{formatDate(r.created_at)}</p>
              </div>
              {score != null && (
                <span className="inline-flex items-center gap-1 px-2 h-7 rounded-md bg-accent/15 text-accent text-[12px] font-semibold tabular-nums border border-accent/25">
                  <Star size={10} fill="currentColor" />
                  {score.toFixed(1)}
                </span>
              )}
            </header>

            <p
              className={`text-[12.5px] text-text-2 leading-relaxed whitespace-pre-line ${
                !isOpen && !isShortContent ? 'line-clamp-4' : ''
              }`}
            >
              {r.content}
            </p>

            <div className="flex items-center justify-between mt-2.5">
              {!isShortContent && (
                <button
                  onClick={() => setExpanded(s => ({ ...s, [r.id]: !s[r.id] }))}
                  className="text-[11px] text-accent hover:text-accent-hover transition-colors font-medium focus-ring rounded px-1 -mx-1"
                >
                  {isOpen ? 'Show less' : 'Read full review'}
                </button>
              )}
              {r.url && (
                <a
                  href={r.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="ml-auto text-[11px] text-text-4 hover:text-text-2 transition-colors flex items-center gap-1"
                >
                  Read on TMDB <ExternalLink size={10} />
                </a>
              )}
            </div>
          </motion.article>
        )
      })}
    </div>
  )
}

function normalizeAvatar(path: string): string {
  // TMDB sometimes returns gravatar-prefixed paths like '/https://...'
  if (path.startsWith('/https')) return path.slice(1)
  return path
}
