import { ExternalLink } from '../../lib/icons'
import type { TmdbExternalIds } from '../../api/tmdb'

interface Props {
  tmdbId?: string | number | null
  type?: 'movie' | 'tv'
  ids?: TmdbExternalIds | null
  jellyfinExternalUrls?: { Name?: string | null; Url?: string | null }[] | null
}

export default function ExternalLinks({ tmdbId, type, ids, jellyfinExternalUrls }: Props) {
  const links: { label: string; href: string; primary?: boolean }[] = []

  if (ids?.imdb_id) {
    links.push({ label: 'IMDb', href: `https://www.imdb.com/title/${ids.imdb_id}/`, primary: true })
  }
  if (tmdbId) {
    links.push({
      label: 'TMDB',
      href: `https://www.themoviedb.org/${type === 'tv' ? 'tv' : 'movie'}/${tmdbId}`,
    })
  }
  if (ids?.wikidata_id) {
    links.push({ label: 'Wikidata', href: `https://www.wikidata.org/wiki/${ids.wikidata_id}` })
  }
  if (ids?.tvdb_id) {
    links.push({ label: 'TVDB', href: `https://thetvdb.com/?tab=series&id=${ids.tvdb_id}` })
  }
  for (const u of jellyfinExternalUrls || []) {
    if (u.Url && u.Name && !links.some(l => l.label === u.Name)) {
      links.push({ label: u.Name, href: u.Url })
    }
  }

  if (!links.length) return null

  return (
    <div className="flex items-center gap-1.5 flex-wrap">
      {links.map(l => (
        <a
          key={l.label}
          href={l.href}
          target="_blank"
          rel="noopener noreferrer"
          className="group inline-flex items-center gap-1.5 h-8 px-2.5 bg-white/8 hover:bg-white/15 backdrop-blur border border-white/10 hover:border-white/20 rounded-md text-[11.5px] text-white/80 hover:text-white font-medium transition-all duration-150 focus-ring"
        >
          {l.label}
          <ExternalLink size={11} className="text-white/45 group-hover:text-white/75 transition-colors" />
        </a>
      ))}
    </div>
  )
}
