import { useMemo } from 'react'
import { useQueries } from '@tanstack/react-query'
import { motion } from 'framer-motion'
import { useNavigate } from 'react-router-dom'
import { CalendarEvent, Star } from '../../lib/icons'
import { discoverMovies, type TmdbMovie } from '../../api/tmdb'

const TMDB_IMG = 'https://image.tmdb.org/t/p'
const YEARS_BACK = [5, 10, 15, 20, 25, 30, 40, 50]

/**
 * "On this day in cinema" rail. For a handful of anniversary windows
 * (5 / 10 / 15... years ago this week), pulls the top-rated film TMDB
 * recorded as released near today's date that year, and renders each as
 * a horizontal card. Self-hides every year-slot with no qualifying
 * release, and hides the whole rail if nothing qualifies anywhere.
 *
 * Uses a +/- 3-day window rather than exact MM-DD because exact-date
 * matches are rare - "this week in cinema history" reads naturally and
 * surfaces enough material to be interesting.
 */
export default function OnThisDay() {
  const navigate = useNavigate()
  const today = useMemo(() => new Date(), [])

  const queries = useMemo(() => {
    const y = today.getFullYear()
    const m = String(today.getMonth() + 1).padStart(2, '0')
    const d = today.getDate()
    const fromD = String(Math.max(1, d - 3)).padStart(2, '0')
    // Clamp upper bound to 28 to avoid edge cases in shorter months.
    const toD = String(Math.min(28, d + 3)).padStart(2, '0')
    return YEARS_BACK.map(yearsAgo => {
      const year = y - yearsAgo
      return {
        yearsAgo,
        year,
        params: {
          'primary_release_date.gte': `${year}-${m}-${fromD}`,
          'primary_release_date.lte': `${year}-${m}-${toD}`,
          'vote_count.gte': '500',
          'vote_average.gte': '7',
          sort_by: 'vote_average.desc',
        },
      }
    })
  }, [today])

  const results = useQueries({
    queries: queries.map(q => ({
      queryKey: ['otd', q.year, q.params],
      queryFn: () => discoverMovies(q.params),
      staleTime: 24 * 60 * 60 * 1000,
    })),
  })

  const picks = useMemo(() => {
    return queries
      .map((q, i) => {
        const res = results[i]?.data
        const top = (res?.results || [])[0] as TmdbMovie | undefined
        if (!top || !top.poster_path) return null
        return { yearsAgo: q.yearsAgo, year: q.year, movie: top }
      })
      .filter((x): x is { yearsAgo: number; year: number; movie: TmdbMovie } => !!x)
  }, [queries, results])

  if (picks.length === 0) return null

  return (
    <section className="mb-8">
      <div className="px-7 mb-3">
        <div className="flex items-center gap-2 mb-1">
          <span className="w-1 h-3.5 rounded-full bg-accent" />
          <span className="text-[10.5px] font-semibold text-text-3 uppercase tracking-[0.18em]">
            This week in cinema
          </span>
        </div>
        <p className="text-[12px] text-text-3 mt-0.5">
          What dropped around {formatToday(today)} - across the decades.
        </p>
      </div>

      <div className="-mx-1 overflow-x-auto hide-scrollbar">
        <ol className="flex items-stretch gap-2.5 px-7 min-w-max">
          {picks.map((pick, i) => (
            <motion.li
              key={pick.year}
              initial={{ opacity: 0, y: 6 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ duration: 0.32, delay: Math.min(i * 0.04, 0.32), ease: [0.16, 1, 0.3, 1] }}
              className="w-[280px] shrink-0"
            >
              <button
                onClick={() => navigate(`/item/tmdb-movie-${pick.movie.id}`)}
                className="group w-full text-left rounded-xl overflow-hidden ring-1 ring-border hover:ring-border-strong transition-all duration-200 bg-elevated/30 flex"
              >
                <div className="w-[88px] shrink-0 aspect-[2/3] overflow-hidden bg-void">
                  {pick.movie.poster_path && (
                    <img
                      src={`${TMDB_IMG}/w300${pick.movie.poster_path}`}
                      alt=""
                      className="w-full h-full object-cover group-hover:scale-[1.04] transition-transform duration-400"
                      loading="lazy"
                    />
                  )}
                </div>
                <div className="flex-1 min-w-0 p-3 flex flex-col">
                  <div className="flex items-center gap-1.5 mb-1.5">
                    <CalendarEvent size={11} className="text-accent shrink-0" />
                    <span className="text-[10px] uppercase tracking-[0.16em] font-semibold text-accent tabular-nums">
                      {pick.yearsAgo} years ago
                    </span>
                  </div>
                  <p className="font-display text-[13.5px] font-bold text-text-1 tracking-tight leading-tight line-clamp-2">
                    {pick.movie.title}
                  </p>
                  <p className="text-[10.5px] text-text-3 mt-auto tabular-nums">
                    Released {formatReleaseDate(pick.movie.release_date)}
                  </p>
                  {typeof pick.movie.vote_average === 'number' && (
                    <span className="mt-1 inline-flex items-center gap-1 text-[10.5px] text-accent tabular-nums">
                      <Star size={9} fill="currentColor" stroke={0} />
                      {pick.movie.vote_average.toFixed(1)}
                    </span>
                  )}
                </div>
              </button>
            </motion.li>
          ))}
        </ol>
      </div>
    </section>
  )
}

function formatToday(d: Date): string {
  return d.toLocaleDateString(undefined, { month: 'long', day: 'numeric' })
}

function formatReleaseDate(iso: string | null | undefined): string {
  if (!iso) return ''
  const d = new Date(iso)
  if (Number.isNaN(d.getTime())) return ''
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' })
}
