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

interface FallbackPerson {
  Id?: string | null
  Name?: string | null
  Role?: string | null
  PrimaryImageTag?: string | null
  Type?: string | null
}

interface Props {
  cast: any[]
  fallbackPeople?: FallbackPerson[] | null
}

export default function CastList({ cast, fallbackPeople }: Props) {
  const navigate = useNavigate()
  const list = cast.length ? cast : (fallbackPeople || []).filter((p: any) => p.Type === 'Actor')

  return (
    <div className="-mx-7">
      <HorizontalScroller gap="gap-2" arrowsBottomInset="bottom-8">
        {list.map((c: any, i: number) => (
          <motion.button
            key={`${c.id ?? c.Id ?? c.name ?? c.Name ?? i}`}
            onClick={() => c.id && navigate(`/person/${c.id}`)}
            initial={{ opacity: 0, y: 6 }}
            animate={{ opacity: 1, y: 0 }}
            transition={{ duration: 0.3, delay: Math.min(i * 0.025, 0.4) }}
            whileHover={{ y: -2 }}
            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">
              {c.profile_path ? (
                <img
                  src={getTmdbImageUrl(c.profile_path, 'w185')}
                  alt={c.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">
                  {(c.name || c.Name || '?')[0]}
                </div>
              )}
            </div>
            <span className="text-[11px] text-text-1 truncate w-full leading-tight font-medium">
              {c.name || c.Name}
            </span>
            {(c.character || c.Role) && (
              <span className="text-[10px] text-text-4 truncate w-full leading-tight mt-0.5">
                {c.character || c.Role}
              </span>
            )}
          </motion.button>
        ))}
      </HorizontalScroller>
    </div>
  )
}
