import { useNavigate } from 'react-router-dom'
import { motion } from 'framer-motion'
import { getTmdbImageUrl, type TmdbCastMember } from '../../api/tmdb'
import HorizontalScroller from '../ui/HorizontalScroller'

interface Props {
  crew: TmdbCastMember[]
  limit?: number
}

const DEPT_ORDER = ['Directing', 'Writing', 'Production', 'Camera', 'Editing', 'Sound', 'Visual Effects', 'Art']

export default function CrewGrid({ crew, limit = 14 }: Props) {
  if (!crew?.length) return null

  // De-duplicate by person id+job and prioritise high-impact departments
  const seen = new Set<string>()
  const top: TmdbCastMember[] = []
  for (const dept of DEPT_ORDER) {
    for (const c of crew) {
      if (c.department !== dept) continue
      const key = `${c.id}-${c.job}`
      if (seen.has(key)) continue
      seen.add(key)
      top.push(c)
      if (top.length >= limit) break
    }
    if (top.length >= limit) break
  }

  if (!top.length) return null

  return (
    <div className="-mx-7">
      <HorizontalScroller gap="gap-2" arrowsBottomInset="bottom-8">
        {top.map((c, i) => (
          <CrewMember key={`${c.id}-${c.credit_id ?? i}`} member={c} index={i} />
        ))}
      </HorizontalScroller>
    </div>
  )
}

function CrewMember({ member, index }: { member: TmdbCastMember; index: number }) {
  const navigate = useNavigate()
  return (
    <motion.button
      initial={{ opacity: 0, y: 6 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3, delay: Math.min(index * 0.025, 0.4) }}
      whileHover={{ y: -2 }}
      onClick={() => member.id && navigate(`/person/${member.id}`)}
      className="flex flex-col items-center text-center shrink-0 w-[88px] group focus-ring rounded-lg p-1"
    >
      <div className="w-16 h-16 rounded-full overflow-hidden bg-elevated mb-2 ring-1 ring-border group-hover:ring-accent/30 transition-all duration-200">
        {member.profile_path ? (
          <img
            src={getTmdbImageUrl(member.profile_path, 'w185')}
            alt={member.name}
            className="w-full h-full object-cover transition-transform duration-300 group-hover:scale-105"
            loading="lazy"
          />
        ) : (
          <div className="w-full h-full grid place-items-center text-text-3 text-[15px] font-display font-semibold bg-gradient-to-br from-elevated to-higher">
            {member.name[0]}
          </div>
        )}
      </div>
      <span className="text-[11px] text-text-1 truncate w-full leading-tight font-medium">{member.name}</span>
      {member.job && (
        <span className="text-[10px] text-text-4 truncate w-full leading-tight mt-0.5">{member.job}</span>
      )}
    </motion.button>
  )
}
