import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { Boxes, ChevronRight, Check } from '../../lib/icons'
import { getTmdbImageUrl, type TmdbCollectionRef, type TmdbCollection } from '../../api/tmdb'
import { useLibraryByTmdbId } from '../../hooks/use-jellyfin'

interface Props {
  collectionRef?: TmdbCollectionRef | null
  collection?: TmdbCollection | null
  currentMovieId?: number | null
}

export default function CollectionStrip({ collectionRef, collection, currentMovieId }: Props) {
  const navigate = useNavigate()
  const { data: libraryMap } = useLibraryByTmdbId()
  const ref = collection || collectionRef
  if (!ref) return null

  // Sort by release date ascending. Items with no release date (or an
  // unparseable one) sort to the END so unannounced sequels don't hijack
  // the #1 slot just because their date field is empty.
  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 inLibraryCount = libraryMap
    ? parts.reduce((acc, p) => acc + (libraryMap.has(String(p.id)) ? 1 : 0), 0)
    : 0

  return (
    <div className="relative overflow-hidden rounded-xl border border-border">
      {/* Backdrop */}
      {ref.backdrop_path && (
        <>
          <div
            className="absolute inset-0 bg-cover bg-center"
            style={{ backgroundImage: `url(${getTmdbImageUrl(ref.backdrop_path, 'w1280')})` }}
          />
          <div className="absolute inset-0 bg-gradient-to-r from-void/95 via-void/85 to-void/55" />
          <div className="absolute inset-0 bg-gradient-to-t from-void/95 to-transparent" />
        </>
      )}
      {!ref.backdrop_path && <div className="absolute inset-0 bg-gradient-to-br from-elevated to-void" />}

      <div className="relative p-5">
        <div className="flex items-center justify-between mb-3 gap-3 flex-wrap">
          <button
            onClick={() => navigate(`/collection/${ref.id}`)}
            className="group flex items-center gap-2 text-left focus-ring rounded-md"
          >
            <Boxes size={14} className="text-accent" />
            <span className="text-[10px] font-semibold uppercase tracking-[0.14em] text-text-3">Part of</span>
            <span className="text-[15px] font-semibold tracking-tight text-white">{ref.name}</span>
            <ChevronRight size={14} className="text-text-3 transition-transform duration-200 group-hover:translate-x-0.5" />
          </button>
          {parts.length > 0 && libraryMap && (
            <span className="text-[11px] text-white/60 tracking-tight">
              <span className="tabular-nums text-white font-semibold">{inLibraryCount}</span>
              <span className="text-white/45"> of </span>
              <span className="tabular-nums text-white">{parts.length}</span>
              <span className="text-white/45"> in your library · watch in release order</span>
            </span>
          )}
        </div>

        {parts.length > 0 ? (
          <div className="flex gap-3 overflow-x-auto hide-scrollbar -mx-1 px-1 py-1">
            {parts.map((m, i) => {
              const isCurrent = currentMovieId != null && m.id === currentMovieId
              const inLibrary = libraryMap?.has(String(m.id)) ?? false
              return (
                <motion.button
                  key={m.id}
                  onClick={() => !isCurrent && navigate(`/item/tmdb-${m.id}`)}
                  initial={{ opacity: 0, y: 6 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3, delay: Math.min(i * 0.04, 0.4) }}
                  whileHover={{ y: -3 }}
                  className={`shrink-0 w-[110px] focus-ring rounded-md text-left ${isCurrent ? 'cursor-default' : ''}`}
                >
                  <div className={`relative aspect-[2/3] rounded-md overflow-hidden bg-elevated ring-1 ${
                    isCurrent ? 'ring-accent' : 'ring-border'
                  }`}>
                    {m.poster_path ? (
                      <img
                        src={getTmdbImageUrl(m.poster_path, 'w300')}
                        alt={m.title}
                        className={`w-full h-full object-cover transition ${
                          inLibrary || isCurrent ? '' : 'opacity-60 saturate-50'
                        }`}
                        loading="lazy"
                      />
                    ) : (
                      <div className="w-full h-full grid place-items-center text-text-3 text-2xl font-display">
                        {m.title?.[0]}
                      </div>
                    )}
                    <span
                      className={`absolute top-1.5 left-1.5 inline-flex items-center justify-center min-w-5 h-5 px-1.5 rounded-full text-[10px] font-bold tabular-nums tracking-tight ${
                        isCurrent
                          ? 'bg-accent text-void'
                          : inLibrary
                            ? 'bg-white/85 text-void'
                            : 'bg-black/60 text-white/80 ring-1 ring-white/15'
                      }`}
                    >
                      {i + 1}
                    </span>
                    {inLibrary && !isCurrent && (
                      <span className="absolute top-1.5 right-1.5 w-5 h-5 rounded-full bg-accent/90 text-void grid place-items-center" title="In your library">
                        <Check size={11} strokeWidth={3} />
                      </span>
                    )}
                    {!inLibrary && !isCurrent && libraryMap && (
                      <span className="absolute bottom-1.5 left-1.5 right-1.5 text-center text-[9px] uppercase tracking-[0.12em] font-semibold text-white/85 bg-black/55 backdrop-blur-sm rounded px-1 py-0.5">
                        Missing
                      </span>
                    )}
                    {isCurrent && (
                      <div className="absolute inset-0 bg-accent/15 grid place-items-end justify-center pb-2">
                        <span className="px-2 h-5 inline-flex items-center bg-accent text-void rounded-full text-[9px] font-bold uppercase tracking-wider">
                          Current
                        </span>
                      </div>
                    )}
                  </div>
                  <p className="text-[11.5px] text-white/90 truncate mt-1.5 font-medium">{m.title}</p>
                  {m.release_date && (
                    <p className="text-[10px] text-white/55 truncate tabular-nums">{m.release_date.slice(0, 4)}</p>
                  )}
                </motion.button>
              )
            })}
          </div>
        ) : (
          <p className="text-[12px] text-text-3 italic">Loading collection...</p>
        )}
      </div>
    </div>
  )
}
