import { useMemo } from 'react'
import { Calendar, Cloud, Disc3, Star, Building2, Globe, Languages } from '../../lib/icons'
import {
  countryLabel,
  flagEmoji,
  formatLongDate,
  formatUsd,
  languageLabel,
} from '../../lib/format'
import { getTmdbImageUrl, type TmdbMovie, type TmdbTvShow } from '../../api/tmdb'
import BrandLogo from '../ui/BrandLogo'

interface Props {
  itemType: 'Movie' | 'Series' | 'Episode' | string | undefined
  movie?: TmdbMovie | null
  tv?: TmdbTvShow | null
  region: string
}

interface ReleaseSplit {
  theatrical: string | null
  digital: string | null
  physical: string | null
  premiere: string | null
}

function pickReleases(movie: TmdbMovie, region: string): ReleaseSplit {
  const empty: ReleaseSplit = {
    theatrical: null,
    digital: null,
    physical: null,
    premiere: null,
  }
  const all = movie.release_dates?.results || []
  const regional = all.find(r => r.iso_3166_1 === region)
  const us = all.find(r => r.iso_3166_1 === 'US')
  const list = regional?.release_dates || us?.release_dates || []
  const out = { ...empty }
  for (const d of list) {
    // type 1 Premiere, 2 Theatrical limited, 3 Theatrical, 4 Digital,
    // 5 Physical, 6 TV
    if (d.type === 3 && !out.theatrical) out.theatrical = d.release_date
    if (d.type === 2 && !out.theatrical) out.theatrical = d.release_date
    if (d.type === 4 && !out.digital) out.digital = d.release_date
    if (d.type === 5 && !out.physical) out.physical = d.release_date
    if (d.type === 1 && !out.premiere) out.premiere = d.release_date
  }
  return out
}

export default function FactsPanel({ itemType, movie, tv, region }: Props) {
  const releases = useMemo(
    () => (movie ? pickReleases(movie, region) : null),
    [movie, region],
  )

  const isMovie = itemType === 'Movie' && !!movie
  const isSeries = itemType === 'Series' && !!tv

  if (!isMovie && !isSeries) return null

  const status = isMovie ? movie?.status : tv?.status
  const originalLanguage = isMovie ? movie?.original_language : tv?.original_language
  const productionCountries = (isMovie
    ? movie?.production_countries
    : tv?.production_countries) || []
  const productionCompanies = (isMovie
    ? movie?.production_companies
    : tv?.production_companies) || []
  const networks = isSeries ? tv?.networks || [] : []
  const tagline = isMovie ? movie?.tagline : tv?.tagline
  const homepage = isMovie ? movie?.homepage : tv?.homepage
  const originalTitle = isMovie
    ? movie?.original_title && movie.original_title !== movie.title
      ? movie.original_title
      : null
    : tv?.original_name && tv?.original_name !== tv?.name
      ? tv.original_name
      : null
  const seriesType = isSeries ? tv?.type : null
  const inProduction = isSeries ? tv?.in_production : null
  const numberOfSeasons = isSeries ? tv?.number_of_seasons : null
  const numberOfEpisodes = isSeries ? tv?.number_of_episodes : null
  const firstAir = isSeries ? tv?.first_air_date : null
  const lastAir = isSeries ? tv?.last_air_date : null

  return (
    <div className="rounded-xl bg-elevated/40 border border-border overflow-hidden">
      {/* Tagline header (if any) */}
      {tagline && (
        <div className="px-5 pt-5 pb-4 border-b border-border/60">
          <p className="font-display text-[15px] italic text-text-2 leading-snug tracking-[-0.005em]">
            "{tagline}"
          </p>
        </div>
      )}

      {/* Ratings now live in the dedicated Reception section near the
          top of the page. About panel sticks to facts: dates, budgets,
          studios, languages, etc. */}

      {/* Facts list */}
      <dl className="divide-y divide-border/60">
        {originalTitle && (
          <Row label="Original title">
            <span className="text-text-1">{originalTitle}</span>
          </Row>
        )}

        {status && (
          <Row label="Status">
            <span className={`inline-flex items-center gap-1.5 ${
              status === 'Released' || status === 'Ended'
                ? 'text-text-1'
                : 'text-accent'
            }`}>
              {(isSeries && inProduction) ||
              status === 'In Production' ||
              status === 'Returning Series' ||
              status === 'Planned' ? (
                <span className="w-1.5 h-1.5 rounded-full bg-accent animate-pulse" />
              ) : null}
              {status}
            </span>
          </Row>
        )}

        {seriesType && (
          <Row label="Type">
            <span className="text-text-1">{seriesType}</span>
          </Row>
        )}

        {/* Movie release dates */}
        {isMovie && releases && (releases.theatrical || releases.digital || releases.physical || releases.premiere) && (
          <Row label="Release dates" alignTop>
            <div className="flex flex-col gap-1.5 text-text-1">
              {releases.theatrical && (
                <DateLine icon={<Calendar size={12} />} label="Theatrical" date={releases.theatrical} />
              )}
              {releases.digital && (
                <DateLine icon={<Cloud size={12} />} label="Digital" date={releases.digital} />
              )}
              {releases.physical && (
                <DateLine icon={<Disc3 size={12} />} label="Physical" date={releases.physical} />
              )}
              {releases.premiere && !releases.theatrical && (
                <DateLine icon={<Star size={12} />} label="Premiere" date={releases.premiere} />
              )}
            </div>
          </Row>
        )}

        {/* Series air dates */}
        {isSeries && firstAir && (
          <Row label="First air date">
            <span className="text-text-1">{formatLongDate(firstAir)}</span>
          </Row>
        )}
        {isSeries && lastAir && lastAir !== firstAir && (
          <Row label="Last air date">
            <span className="text-text-1">{formatLongDate(lastAir)}</span>
          </Row>
        )}
        {isSeries && (numberOfSeasons || numberOfEpisodes) && (
          <Row label="Run length">
            <span className="text-text-1 tabular-nums">
              {numberOfSeasons ? `${numberOfSeasons} season${numberOfSeasons === 1 ? '' : 's'}` : ''}
              {numberOfSeasons && numberOfEpisodes ? ' · ' : ''}
              {numberOfEpisodes ? `${numberOfEpisodes} episode${numberOfEpisodes === 1 ? '' : 's'}` : ''}
            </span>
          </Row>
        )}

        {/* Money */}
        {isMovie && movie?.revenue ? (
          <Row label="Revenue">
            <span className="text-text-1 tabular-nums">{formatUsd(movie.revenue)}</span>
          </Row>
        ) : null}
        {isMovie && movie?.budget ? (
          <Row label="Budget">
            <span className="text-text-1 tabular-nums">{formatUsd(movie.budget)}</span>
          </Row>
        ) : null}

        {/* Language + country */}
        {originalLanguage && (
          <Row label="Original language">
            <span className="inline-flex items-center gap-1.5 text-text-1">
              <Languages size={12} className="text-text-3" />
              {languageLabel(originalLanguage)}
            </span>
          </Row>
        )}
        {productionCountries.length > 0 && (
          <Row label={productionCountries.length > 1 ? 'Production countries' : 'Production country'} alignTop>
            <div className="flex flex-col gap-0.5">
              {productionCountries.slice(0, 4).map(c => (
                <span key={c.iso_3166_1} className="inline-flex items-center gap-1.5 text-text-1">
                  <span aria-hidden className="text-[14px] leading-none">
                    {flagEmoji(c.iso_3166_1) || <Globe size={12} className="text-text-3" />}
                  </span>
                  {countryLabel(c.iso_3166_1) || c.name}
                </span>
              ))}
            </div>
          </Row>
        )}

        {/* Studios + networks */}
        {productionCompanies.length > 0 && (
          <Row label={productionCompanies.length > 1 ? 'Studios' : 'Studio'} alignTop>
            <div className="flex flex-col gap-1.5">
              {productionCompanies.slice(0, 4).map(c => (
                <span key={c.id} className="inline-flex items-center gap-2 text-text-1">
                  {c.logo_path ? (
                    <BrandLogo
                      src={getTmdbImageUrl(c.logo_path, 'w92')}
                      alt={c.name}
                      height={14}
                      maxWidth={80}
                    />
                  ) : (
                    <Building2 size={12} className="text-text-3" />
                  )}
                  <span className="truncate">{c.name}</span>
                </span>
              ))}
            </div>
          </Row>
        )}
        {networks.length > 0 && (
          <Row label={networks.length > 1 ? 'Networks' : 'Network'} alignTop>
            <div className="flex flex-col gap-1.5">
              {networks.slice(0, 4).map(n => (
                <span key={n.id} className="inline-flex items-center gap-2 text-text-1">
                  {n.logo_path ? (
                    <BrandLogo
                      src={getTmdbImageUrl(n.logo_path, 'w92')}
                      alt={n.name}
                      height={14}
                      maxWidth={80}
                    />
                  ) : (
                    <Building2 size={12} className="text-text-3" />
                  )}
                  <span className="truncate">{n.name}</span>
                </span>
              ))}
            </div>
          </Row>
        )}

        {homepage && (
          <Row label="Homepage">
            <a
              href={homepage}
              target="_blank"
              rel="noopener noreferrer"
              className="text-accent hover:text-accent-hover transition truncate inline-block max-w-full"
            >
              {homepage.replace(/^https?:\/\//, '').replace(/\/$/, '')}
            </a>
          </Row>
        )}
      </dl>
    </div>
  )
}

function Row({
  label,
  children,
  alignTop = false,
}: {
  label: string
  children: React.ReactNode
  alignTop?: boolean
}) {
  return (
    <div className={`flex gap-4 px-5 py-3 ${alignTop ? 'items-start' : 'items-center'}`}>
      <dt className="w-32 shrink-0 text-[11.5px] font-semibold text-text-3 uppercase tracking-[0.12em]">
        {label}
      </dt>
      <dd className="flex-1 min-w-0 text-[13.5px] tracking-tight">{children}</dd>
    </div>
  )
}

function DateLine({ icon, label, date }: { icon: React.ReactNode; label: string; date: string }) {
  return (
    <span className="inline-flex items-center gap-2 tabular-nums">
      <span className="w-4 h-4 grid place-items-center text-text-3">{icon}</span>
      <span className="text-[10.5px] text-text-3 uppercase tracking-[0.14em] w-[78px]">{label}</span>
      <span>{formatLongDate(date)}</span>
    </span>
  )
}

