import { useState, useEffect } from 'react'
import { Disc, Cpu, Globe, Tv, CheckCircle, ArrowRight } from 'lucide-react'
import { api } from '../lib/api'
import { useDarkMode } from '../context/ThemeContext'
import { MEDIA_SERVER_OPTIONEN } from '../lib/mediaServer'

// Erster Start: Rippy universell einrichten (Commander-Ziel: All-in-one,
// weitergebbar — keine Handarbeit in .env-Dateien nötig).

interface WorkerInfo {
  name: string
  encoders: string[]
  last_seen?: string
}

const ENCODER_LABELS: Record<string, string> = {
  'cpu-x264': 'CPU · H.264 (x264)',
  'cpu-x265': 'CPU · H.265 (x265)',
  'vaapi': 'Hardware · VAAPI (AMD/Intel)',
  'nvenc': 'Hardware · NVENC (NVIDIA)',
}

export default function FirstRunWizard({ onDone }: { onDone: () => void }) {
  const [tmdbKey, setTmdbKey] = useState('')
  const [omdbKey, setOmdbKey] = useState('')
  const [mediaServer, setMediaServer] = useState('jellyfin')
  const [transcodeEnabled, setTranscodeEnabled] = useState(true)
  const [preset, setPreset] = useState('H.265 MKV 1080p30')
  const [workers, setWorkers] = useState<WorkerInfo[]>([])
  const [saving, setSaving] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const { theme } = useDarkMode()

  useEffect(() => {
    api.get('/capabilities')
      .then(r => setWorkers(r.data.workers || []))
      .catch(() => setWorkers([]))
  }, [])

  const abschliessen = async () => {
    setSaving(true)
    setError(null)
    try {
      const bestehende = (await api.get('/settings')).data || {}
      await api.post('/settings', {
        ...bestehende,
        ...(tmdbKey ? { tmdbApiKey: tmdbKey } : {}),
        ...(omdbKey ? { omdbApiKey: omdbKey } : {}),
        mediaServer,
        transcodeEnabled,
        transcodePreset: preset,
      })
      await api.post('/setup/complete')
      onDone()
    } catch {
      setError('Speichern fehlgeschlagen — läuft die API?')
    } finally {
      setSaving(false)
    }
  }

  const feldKlasse = `w-full px-3 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'}`

  return (
    <div className={`min-h-screen flex items-center justify-center p-6 ${theme === 'dark' ? 'bg-slate-950' : 'bg-slate-100'}`}>
      <div className={`w-full max-w-2xl rounded-2xl shadow-2xl overflow-hidden ${theme === 'dark' ? 'bg-slate-900 border border-slate-800' : 'bg-white'}`}>
        <div className="bg-gradient-to-r from-indigo-600 to-purple-700 p-8 text-white">
          <div className="flex items-center gap-3 mb-2">
            <Disc size={32} />
            <h1 className="text-2xl font-bold">Willkommen bei Rippy</h1>
          </div>
          <p className="opacity-90">Einmalige Einrichtung — dauert keine zwei Minuten. Alles ist später unter Einstellungen änderbar.</p>
        </div>

        <div className="p-8 space-y-8">
          {/* Metadaten-APIs */}
          <section>
            <h2 className={`flex items-center gap-2 text-lg font-semibold mb-3 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Globe size={18} className="text-indigo-500" /> Metadaten-Erkennung
            </h2>
            <div className="space-y-3">
              <div>
                <label className={`block text-sm font-medium mb-1 ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  TMDB API-Key <span className="text-indigo-500">(empfohlen)</span>
                </label>
                <input type="password" value={tmdbKey} onChange={e => setTmdbKey(e.target.value)} className={feldKlasse} placeholder="Kostenlos auf themoviedb.org" />
              </div>
              <div>
                <label className={`block text-sm font-medium mb-1 ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  OMDb API-Key <span className={theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}>(optional, zweite Quelle)</span>
                </label>
                <input type="password" value={omdbKey} onChange={e => setOmdbKey(e.target.value)} className={feldKlasse} placeholder="Kostenlos auf omdbapi.com" />
              </div>
              <p className={`text-xs ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>
                Ohne Keys rippt Rippy trotzdem — Discs heißen dann nur wie ihr Volume-Label.
              </p>
            </div>
          </section>

          {/* Media-Server: worauf soll Rippy die Ablage vorbereiten? */}
          <section>
            <h2 className={`flex items-center gap-2 text-lg font-semibold mb-3 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Tv size={18} className="text-indigo-500" /> Dein Media-Server
            </h2>
            <p className={`text-sm mb-3 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
              Rippy benennt fertige Rips als „Titel (Jahr)" und legt für Jellyfin/Emby/Kodi
              zusätzlich movie.nfo + poster.jpg dazu — dein Server erkennt alles ohne Nacharbeit.
            </p>
            <div className="grid grid-cols-2 md:grid-cols-5 gap-2">
              {MEDIA_SERVER_OPTIONEN.map(o => (
                <button
                  key={o.wert}
                  type="button"
                  onClick={() => setMediaServer(o.wert)}
                  title={o.hinweis}
                  className={`px-3 py-2 rounded-lg text-sm font-medium border transition-all ${
                    mediaServer === o.wert
                      ? theme === 'dark'
                        ? 'bg-indigo-900/40 border-indigo-500 text-indigo-300'
                        : 'bg-indigo-50 border-indigo-600 text-indigo-700'
                      : theme === 'dark'
                        ? 'bg-slate-800 border-slate-700 text-slate-400 hover:border-slate-600'
                        : 'bg-slate-50 border-slate-200 text-slate-600 hover:border-slate-300'
                  }`}
                >
                  {o.label}
                </button>
              ))}
            </div>
            <p className={`text-xs mt-2 ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>
              {MEDIA_SERVER_OPTIONEN.find(o => o.wert === mediaServer)?.hinweis}
            </p>
          </section>

          {/* Verarbeitung + erkannte Hardware */}
          <section>
            <h2 className={`flex items-center gap-2 text-lg font-semibold mb-3 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Cpu size={18} className="text-indigo-500" /> Verarbeitung
            </h2>

            <div className={`rounded-lg p-4 mb-3 ${theme === 'dark' ? 'bg-slate-800' : 'bg-slate-50'}`}>
              <p className={`text-sm font-medium mb-2 ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>Erkannte Encoder in deinem System:</p>
              {workers.length === 0 ? (
                <p className={`text-sm ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>Noch kein Worker gemeldet — startet gerade?</p>
              ) : (
                workers.map(w => (
                  <div key={w.name} className="mb-1">
                    <span className={`text-xs font-mono ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>{w.name}: </span>
                    {w.encoders.map(e => (
                      <span key={e} className={`inline-block text-xs px-2 py-0.5 rounded mr-1 ${e.startsWith('cpu') ? (theme === 'dark' ? 'bg-slate-700 text-slate-300' : 'bg-slate-200 text-slate-600') : 'bg-emerald-600/20 text-emerald-500 font-medium'}`}>
                        {ENCODER_LABELS[e] || e}
                      </span>
                    ))}
                  </div>
                ))
              )}
              <p className={`text-xs mt-2 ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>
                Tipp: GPU-Maschinen im Netz können als optionale Transcode-Worker angebunden werden (siehe README).
              </p>
            </div>

            <label className={`flex items-center gap-3 mb-3 text-sm ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
              <input type="checkbox" checked={transcodeEnabled} onChange={e => setTranscodeEnabled(e.target.checked)} className="w-4 h-4 accent-indigo-600" />
              Nach dem Rip auf Arbeitsgröße komprimieren (empfohlen — sonst ~40 GB pro Blu-ray)
            </label>

            {transcodeEnabled && (
              <select value={preset} onChange={e => setPreset(e.target.value)} className={feldKlasse}>
                <option value="H.265 MKV 1080p30">H.265 — klein &amp; modern (Standard)</option>
                <option value="HQ 1080p30 Surround">H.264 — schneller auf schwacher CPU, etwas größer</option>
              </select>
            )}
          </section>

          {error && <p className="text-sm text-rose-500">{error}</p>}

          <button
            onClick={abschliessen}
            disabled={saving}
            className="w-full flex items-center justify-center gap-2 px-6 py-3 bg-indigo-600 text-white rounded-lg font-medium hover:bg-indigo-700 transition-colors disabled:opacity-50"
          >
            {saving ? 'Speichern…' : <>Los geht's <ArrowRight size={18} /></>}
          </button>

          <p className={`text-xs text-center flex items-center justify-center gap-1 ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>
            <CheckCircle size={12} /> Läuft komplett lokal — keine Cloud, keine Telemetrie.
          </p>
        </div>
      </div>
    </div>
  )
}
