import { ExternalLink } from '../../../lib/icons'
import { Section, Row, Input, type PrefsLike } from '../_ui'
import { writeSecret } from '../../../lib/sensitive-storage'

export function TmdbSection({ prefs }: { prefs: PrefsLike }) {
  const builtIn = (import.meta.env.VITE_TMDB_API_KEY || '').trim()
  const usingBuiltIn = !prefs.tmdbApiKey && !!builtIn
  return (
    <Section
      id="tmdb"
      title="TMDB"
      description={
        usingBuiltIn
          ? 'Built-in key in use - the app works out of the box. Override below if you have your own.'
          : 'Enriches movies and shows with metadata, art, and ratings'
      }
    >
      {usingBuiltIn && (
        <div className="py-2 px-3 rounded-md bg-accent/10 border border-accent/20 text-[12px] text-text-2 mb-2">
          A built-in TMDB key is bundled with this build, so metadata, posters, trailers, and discovery rows all work without setup. Add your own key below only if you want to use a personal key.
        </div>
      )}
      <Row label="API key" hint={usingBuiltIn ? 'Override the built-in key with your own' : 'Free key from themoviedb.org/settings/api'}>
        <Input
          type="password"
          value={prefs.tmdbApiKey}
          onChange={v => {
            prefs.setPreference('tmdbApiKey', v)
            try { writeSecret('jf_tmdb_key', v) } catch { /* noop */ }
          }}
          placeholder={usingBuiltIn ? 'Optional - leave blank to use built-in' : 'Paste your key'}
          width="w-64"
        />
      </Row>
      <div className="py-3 -mx-4 px-4 text-[11.5px] text-text-3 flex items-center justify-between gap-4 border-t border-border/50">
        <span>Don't have one yet?</span>
        <a
          href="https://www.themoviedb.org/settings/api"
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1 text-accent hover:text-accent-hover transition-colors font-medium"
        >
          Get a TMDB API key
          <ExternalLink size={11} />
        </a>
      </div>
    </Section>
  )
}
