import { useParams, useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Boxes, Calendar } from '../lib/icons'
import { useTmdbCollection } from '../hooks/use-tmdb'
import { getTmdbImageUrl } from '../api/tmdb'
import { usePosterGridClasses } from '../lib/density'

export default function CollectionPage() {
  const { id } = useParams<{ id: string }>()
  const navigate = useNavigate()
  const { data: collection, isLoading } = useTmdbCollection(id)
  const gridCls = usePosterGridClasses()

  if (isLoading) return <CollectionSkeleton />
  if (!collection) {
    return (
      <div className="flex flex-col items-center justify-center h-[60vh] text-center px-6">
        <p className="text-text-2 text-[15px] mb-1">Collection not found</p>
      </div>
    )
  }

  // Sort by release date ascending; items with no/unparseable date sort
  // to the end so unannounced sequels don't end up at #1.
  const parts = (collection.parts || []).slice().sort((a, b) => {
    const ta = a.release_date ? Date.parse(a.release_date) : NaN
    const tb = b.release_date ? Date.parse(b.release_date) : NaN
    const da = Number.isFinite(ta) ? ta : Number.POSITIVE_INFINITY
    const db = Number.isFinite(tb) ? tb : Number.POSITIVE_INFINITY
    return da - db
  })

  const totalRuntime = parts.reduce((sum, p) => sum + (p.runtime || 0), 0)
  const avgRating =
    parts.length > 0
      ? parts.reduce((sum, p) => sum + (p.vote_average || 0), 0) / parts.length
      : 0

  return (
    <div className="pb-12">
      {/* Hero */}
      <div className="relative h-[50vh] min-h-[380px] -mt-14 overflow-hidden">
        {collection.backdrop_path && (
          <motion.div
            initial={{ scale: 1.06, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            transition={{ duration: 1.4, ease: [0.16, 1, 0.3, 1] }}
            className="absolute inset-0 bg-cover bg-top"
            style={{ backgroundImage: `url(${getTmdbImageUrl(collection.backdrop_path, 'w1920')})` }}
          />
        )}
        <div className="absolute inset-0 bg-gradient-to-r from-void via-void/65 to-void/15" />
        <div className="absolute inset-0 bg-gradient-to-t from-void via-void/30 to-transparent" />

        <div className="relative h-full flex items-end pb-12 px-7">
          <motion.div
            initial={{ opacity: 0, y: 14 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.6, ease: [0.16, 1, 0.3, 1], delay: 0.15 }}
            className="max-w-3xl"
          >
            <span className="inline-flex items-center gap-1.5 h-6 px-2.5 rounded-full bg-accent/12 border border-accent/30 text-accent text-[10px] font-semibold uppercase tracking-[0.12em] mb-3">
              <Boxes size={10} />
              Collection
            </span>
            <h1 className="font-display text-4xl md:text-5xl font-bold text-white tracking-tight leading-[1] mb-3 drop-shadow-[0_4px_16px_rgba(0,0,0,0.6)]">
              {collection.name}
            </h1>
            <div className="flex items-center gap-3 text-[12px] text-white/70 font-medium mb-3 flex-wrap">
              <span>{parts.length} {parts.length === 1 ? 'film' : 'films'}</span>
              {totalRuntime > 0 && (
                <>
                  <span className="text-white/30">·</span>
                  <span className="tabular-nums">
                    {Math.floor(totalRuntime / 60)}h {totalRuntime % 60}m total
                  </span>
                </>
              )}
              {avgRating > 0 && (
                <>
                  <span className="text-white/30">·</span>
                  <span className="tabular-nums">{avgRating.toFixed(1)} avg rating</span>
                </>
              )}
            </div>
            {collection.overview && (
              <p className="text-[14px] text-white/80 leading-relaxed line-clamp-3 max-w-2xl">
                {collection.overview}
              </p>
            )}
          </motion.div>
        </div>
        <div className="absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-b from-transparent to-void pointer-events-none" />
      </div>

      {/* Films */}
      <div className="px-7 pt-2">
        <div className="flex items-center gap-2 mb-4">
          <span className="w-1 h-3.5 rounded-full bg-accent" />
          <h3 className="text-[11px] font-semibold text-text-2 uppercase tracking-[0.14em]">In order of release</h3>
        </div>

        <div className={gridCls}>
          {parts.map((m, i) => (
            <motion.button
              key={m.id}
              onClick={() => navigate(`/item/tmdb-${m.id}`)}
              initial={{ opacity: 0, y: 8 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.3, delay: Math.min(i * 0.04, 0.4) }}
              whileHover={{ y: -3 }}
              className="group text-left focus-ring rounded-lg"
            >
              <div className="relative aspect-[2/3] rounded-lg overflow-hidden bg-elevated ring-1 ring-border group-hover:ring-accent/40 transition-all duration-200">
                {m.poster_path ? (
                  <img
                    src={getTmdbImageUrl(m.poster_path, 'w300')}
                    alt={m.title}
                    loading="lazy"
                    className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
                  />
                ) : (
                  <div className="w-full h-full grid place-items-center text-text-3 text-2xl font-display">
                    {m.title?.[0]}
                  </div>
                )}
                <div className="absolute top-1.5 left-1.5">
                  <span className="inline-flex items-center h-[18px] px-1.5 rounded text-[9px] font-bold bg-black/55 backdrop-blur text-white border border-white/10 tabular-nums">
                    {i + 1}
                  </span>
                </div>
              </div>
              <p className="text-[12.5px] font-medium text-text-1 truncate mt-2 leading-tight tracking-tight">
                {m.title}
              </p>
              <p className="text-[11px] text-text-3 truncate mt-0.5 inline-flex items-center gap-1">
                <Calendar size={9} />
                {m.release_date ? m.release_date.slice(0, 4) : 'TBA'}
              </p>
            </motion.button>
          ))}
        </div>
      </div>
    </div>
  )
}

function CollectionSkeleton() {
  const gridCls = usePosterGridClasses()
  return (
    <div className="pb-12">
      <div className="relative h-[50vh] min-h-[380px] -mt-14 overflow-hidden">
        <div className="absolute inset-0 skeleton" />
        <div className="absolute inset-0 bg-gradient-to-r from-void to-void/30" />
        <div className="relative h-full flex items-end pb-12 px-7">
          <div className="space-y-3">
            <div className="skeleton h-5 w-24 rounded" />
            <div className="skeleton h-12 w-96 rounded" />
            <div className="skeleton h-3 w-72 rounded" />
          </div>
        </div>
      </div>
      <div className="px-7 pt-6">
        <div className={gridCls}>
          {Array.from({ length: 12 }).map((_, i) => (
            <div key={i}>
              <div className="skeleton aspect-[2/3] rounded-lg" />
              <div className="skeleton h-3 w-3/4 mt-2 rounded" />
              <div className="skeleton h-2.5 w-1/2 mt-1 rounded" />
            </div>
          ))}
        </div>
      </div>
    </div>
  )
}
