import { motion } from 'framer-motion'
import { Calendar, Play, Radio, User, ExternalLink } from '../../lib/icons'
import type { TmdbTvShow, TmdbEpisode } from '../../api/tmdb'
import { getTmdbImageUrl } from '../../api/tmdb'
import type { TvmazeShow } from '../../api/tvmaze'
import { formatDate, formatRelative } from '../../lib/format'
import BrandLogo from '../ui/BrandLogo'

interface Props {
  show?: TmdbTvShow | null
  tvmazeShow?: TvmazeShow | null
  jellyfinAirDays?: string[] | null
  jellyfinAirTime?: string | null
}

export default function SeriesStatusBlock({
  show,
  tvmazeShow,
  jellyfinAirDays,
  jellyfinAirTime,
}: Props) {
  if (!show) return null

  const status = show.status
  const networks = show.networks || []
  const creators = show.created_by || []
  const last = show.last_episode_to_air
  const next = show.next_episode_to_air

  // Schedule fallback chain: Jellyfin's own air metadata > TVmaze schedule.
  // TVmaze provides days as e.g. ['Tuesday'] and time as 'HH:mm'.
  const tvmazeDays = tvmazeShow?.schedule?.days || []
  const tvmazeTime = tvmazeShow?.schedule?.time || ''
  const airDays = jellyfinAirDays && jellyfinAirDays.length > 0 ? jellyfinAirDays : tvmazeDays
  const airTime = jellyfinAirTime || tvmazeTime

  const officialSite = tvmazeShow?.officialSite || null
  const tvmazeRuntime = tvmazeShow?.averageRuntime || tvmazeShow?.runtime || null

  const hasAny =
    !!status ||
    networks.length > 0 ||
    creators.length > 0 ||
    last ||
    next ||
    (airDays && airDays.length > 0) ||
    !!officialSite

  if (!hasAny) return null

  return (
    <div>
      {/* ── Frameless stats strip ─────────────────────────────── */}
      <div className="flex flex-wrap gap-x-10 gap-y-5 pb-5 mb-5 border-b border-border">
        {status && (
          <Stat
            icon={<Radio size={11} className="text-text-3" strokeWidth={2} />}
            label="Status"
          >
            <StatusValue status={status} />
          </Stat>
        )}

        {networks.length > 0 && (
          <Stat
            icon={<NetworkGlyph />}
            label={networks.length > 1 ? 'Networks' : 'Network'}
          >
            <div className="flex flex-col gap-1">
              <div className="flex items-center gap-2 flex-wrap">
                {networks.slice(0, 4).map(n => (
                  n.logo_path ? (
                    <BrandLogo
                      key={n.id}
                      src={getTmdbImageUrl(n.logo_path, 'w92')}
                      alt={n.name}
                      height={14}
                      maxWidth={64}
                    />
                  ) : (
                    <span
                      key={n.id}
                      className="text-[11.5px] text-text-1 font-semibold tracking-tight"
                      title={n.name}
                    >
                      {n.name}
                    </span>
                  )
                ))}
              </div>
              {(airDays?.length || airTime) && (
                <span className="inline-flex items-center gap-1.5 text-[11px] text-text-3 -mt-0.5">
                  <Calendar size={10} className="text-text-4" />
                  {airDays?.join(', ')}
                  {airTime ? ` · ${airTime}` : ''}
                  {tvmazeRuntime ? ` · ${tvmazeRuntime}m` : ''}
                </span>
              )}
              {officialSite && (
                <a
                  href={officialSite}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center gap-1 text-[11px] text-accent hover:text-accent-hover transition-colors -mt-0.5 self-start focus-ring rounded"
                >
                  Official site
                  <ExternalLink size={9} />
                </a>
              )}
            </div>
          </Stat>
        )}

        {creators.length > 0 && (
          <Stat
            icon={<User size={11} className="text-text-3" strokeWidth={2} />}
            label={creators.length > 1 ? 'Created by' : 'Creator'}
          >
            <span className="text-[13px] text-text-1 font-semibold tracking-tight">
              {creators.map(c => c.name).join(', ')}
            </span>
          </Stat>
        )}
      </div>

      {/* ── Episode features ─────────────────────────────────── */}
      {(last || next) && (
        <div className={`grid gap-4 ${last && next ? 'md:grid-cols-2' : ''}`}>
          {last && <EpisodeFeature ep={last} label="Last episode" tone="muted" />}
          {next && <EpisodeFeature ep={next} label="Next episode" tone="accent" />}
        </div>
      )}
    </div>
  )
}

function Stat({
  icon,
  label,
  children,
}: {
  icon: React.ReactNode
  label: string
  children: React.ReactNode
}) {
  return (
    <div className="min-w-0">
      <div className="flex items-center gap-1.5 mb-1.5 leading-none">
        {icon}
        <p className="text-[10px] uppercase tracking-[0.16em] font-semibold text-text-3">
          {label}
        </p>
      </div>
      {children}
    </div>
  )
}

function StatusValue({ status }: { status: string }) {
  const tone =
    status === 'Returning Series' ? { dot: 'bg-success', text: 'text-success', label: 'Airing' }
    : status === 'In Production' ? { dot: 'bg-cool', text: 'text-cool', label: status }
    : status === 'Ended' ? { dot: 'bg-text-3', text: 'text-text-1', label: status }
    : status === 'Canceled' ? { dot: 'bg-error', text: 'text-error', label: status }
    : { dot: 'bg-text-3', text: 'text-text-1', label: status }

  return (
    <span className="inline-flex items-center gap-2">
      <span className={`relative flex h-2 w-2`}>
        <span className={`absolute inline-flex h-full w-full rounded-full ${tone.dot}`} />
        {tone.label === 'Airing' && (
          <span className={`absolute inline-flex h-full w-full rounded-full ${tone.dot} animate-ping opacity-75`} />
        )}
      </span>
      <span className={`text-[13px] font-semibold tracking-tight ${tone.text}`}>{tone.label}</span>
    </span>
  )
}

function NetworkGlyph() {
  // Simple broadcast/wave glyph - matches Tabler icon stroke style
  return (
    <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" className="text-text-3" aria-hidden>
      <path d="M5 16a8 8 0 0 1 14 0" />
      <path d="M8 16a5 5 0 0 1 8 0" />
      <circle cx="12" cy="16" r="1" />
    </svg>
  )
}

function EpisodeFeature({
  ep,
  label,
  tone,
}: {
  ep: TmdbEpisode
  label: string
  tone: 'muted' | 'accent'
}) {
  const still = ep.still_path ? getTmdbImageUrl(ep.still_path, 'w500') : ''
  const labelCls = tone === 'accent' ? 'text-accent' : 'text-text-3'

  return (
    <motion.button
      type="button"
      onClick={() => {/* could navigate to episode if we had a Jellyfin id */}}
      initial={{ opacity: 0, y: 6 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.4, ease: [0.16, 1, 0.3, 1] }}
      className="group flex gap-4 p-2.5 rounded-lg hover:bg-glass-light transition-colors text-left focus-ring"
    >
      <div className="relative w-[180px] aspect-video rounded-md overflow-hidden bg-elevated shrink-0 ring-1 ring-border">
        {still ? (
          <img
            src={still}
            alt={ep.name}
            loading="lazy"
            className="w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.04]"
          />
        ) : (
          <div className="w-full h-full grid place-items-center text-text-4">
            <span className="font-display text-2xl font-bold opacity-50">
              E{ep.episode_number}
            </span>
          </div>
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/55 via-black/0 to-transparent" />
        {tone === 'accent' && (
          <div className="absolute inset-0 ring-1 ring-accent/40 rounded-md" />
        )}
        <div className="absolute bottom-1.5 left-2 text-[10px] font-mono font-bold text-white/95 tabular-nums tracking-wider">
          S{ep.season_number} · E{ep.episode_number}
        </div>
      </div>

      <div className="flex-1 min-w-0 py-0.5">
        <p className={`text-[10px] uppercase tracking-[0.16em] font-semibold ${labelCls} mb-1.5 leading-none`}>
          {label}
        </p>
        <p className="text-[14.5px] text-text-1 font-semibold tracking-tight leading-tight line-clamp-2">
          {ep.name}
        </p>
        <p className="text-[11.5px] text-text-3 mt-2 flex items-center gap-1.5 tabular-nums">
          <Calendar size={10} className="text-text-4" />
          {ep.air_date ? formatDate(ep.air_date) : 'TBA'}
          {ep.air_date && (
            <>
              <span className="text-text-5">·</span>
              <span className={tone === 'accent' ? 'text-accent' : ''}>
                {formatRelative(ep.air_date)}
              </span>
            </>
          )}
        </p>
        {ep.runtime && (
          <p className="text-[11px] text-text-4 mt-1 tabular-nums">{ep.runtime}m</p>
        )}
        {tone === 'accent' && (
          <p className="text-[11px] text-accent font-medium mt-2 inline-flex items-center gap-1">
            <Play size={10} fill="currentColor" />
            Premieres soon
          </p>
        )}
      </div>
    </motion.button>
  )
}
