import { motion } from 'framer-motion'
import { useTmdbEpisode, useTmdbTvShow } from '../../hooks/use-tmdb'
import { useItemDetails } from '../../hooks/use-jellyfin'
import { getTmdbImageUrl } from '../../api/tmdb'
import type { BaseItemDto } from '../../api/types'
import HorizontalScroller from '../ui/HorizontalScroller'
import ReviewsSection from './ReviewsSection'

interface Props {
  item: BaseItemDto
}

/**
 * Extra sections rendered on episode-type detail pages:
 *
 * 1. **Featured in this episode** - per-episode TMDB cast filtered to the
 *    guest stars (people not in the main show ensemble). Falls back to
 *    nothing if TMDB doesn't have credits for the episode.
 * 2. **Directed / Written by** - inline line below the cast row.
 * 3. **Series reviews** - the show's TMDB reviews with a "from the
 *    series" caption, since TMDB doesn't expose per-episode reviews.
 *
 * Renders nothing if the parent series has no TMDB id, so non-TMDB
 * libraries are unaffected.
 */
export default function EpisodeExtras({ item }: Props) {
  const seriesJfId = item.SeriesId ?? undefined
  const { data: seriesItem } = useItemDetails(seriesJfId)
  const seriesTmdbId = seriesItem?.ProviderIds?.Tmdb
  const seriesTmdbNum = seriesTmdbId ? Number(seriesTmdbId) : null
  const seasonNum = item.ParentIndexNumber ?? undefined
  const episodeNum = item.IndexNumber ?? undefined

  const tvShow = useTmdbTvShow(seriesTmdbNum)
  const episode = useTmdbEpisode(seriesTmdbNum, seasonNum, episodeNum)

  if (!seriesTmdbNum) return null

  const credits = episode.data?.credits
  const mainCastIds = new Set((tvShow.data?.credits?.cast || []).map(c => c.id))
  // Surface guest stars first; pad with episode-specific cast that aren't
  // in the main ensemble. Cap at 8.
  const guests = (credits?.cast || []).filter(c => !mainCastIds.has(c.id)).slice(0, 8)
  const crew = credits?.crew || []
  const director = crew.find(c => c.job === 'Director')
  const writer = crew.find(
    c => c.job === 'Writer' || c.job === 'Screenplay' || c.job === 'Story',
  )

  const reviews = tvShow.data?.reviews?.results || []

  return (
    <>
      {(guests.length > 0 || director || writer) && (
        <motion.section
          initial={{ opacity: 0, y: 8 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.32, ease: [0.16, 1, 0.3, 1] }}
        >
          <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-3 leading-none">
            Featured in this episode
          </p>
          {guests.length > 0 && (
            <div className="-mx-7 mb-2">
              <HorizontalScroller gap="gap-3" arrowsBottomInset="bottom-12">
                {guests.map(c => (
                  <div key={c.id} className="shrink-0 w-[112px]">
                    <div className="aspect-[2/3] rounded-lg overflow-hidden bg-elevated ring-1 ring-border mb-1.5">
                      {c.profile_path ? (
                        <img
                          src={getTmdbImageUrl(c.profile_path, 'w185')}
                          alt={c.name}
                          className="w-full h-full object-cover"
                        />
                      ) : (
                        <div className="w-full h-full grid place-items-center text-text-4 text-2xl font-display font-semibold opacity-40">
                          {c.name?.[0]?.toUpperCase() || '?'}
                        </div>
                      )}
                    </div>
                    <p className="text-[12px] text-text-1 font-medium leading-tight tracking-tight truncate">
                      {c.name}
                    </p>
                    {c.character && (
                      <p className="text-[10.5px] text-text-3 leading-tight truncate">
                        {c.character}
                      </p>
                    )}
                  </div>
                ))}
              </HorizontalScroller>
            </div>
          )}
          {(director || writer) && (
            <p className="text-[12px] text-text-3 leading-relaxed">
              {director && (
                <>
                  Directed by <span className="text-text-1 font-medium">{director.name}</span>
                </>
              )}
              {director && writer && <span className="text-text-5 mx-2">·</span>}
              {writer && (
                <>
                  Written by <span className="text-text-1 font-medium">{writer.name}</span>
                </>
              )}
            </p>
          )}
        </motion.section>
      )}

      {reviews.length > 0 && (
        <section>
          <p className="text-[10px] uppercase tracking-[0.18em] font-semibold text-text-3 mb-1 leading-none">
            Reviews
          </p>
          <p className="text-[11px] text-text-4 mb-4">From the series</p>
          <ReviewsSection reviews={reviews} />
        </section>
      )}
    </>
  )
}
