import { useState, useEffect } from 'react'
import { Search, Loader2, X, Film } from 'lucide-react'
import { api } from '../lib/api'
import { useDarkMode } from '../context/ThemeContext'

// „Nicht korrekt?!"-Popup (Commander-Wunsch 23.07.): Korrektur direkt am
// Dashboard — suchen, richtigen Treffer anklicken, Rippy merkt sich die Wahl
// für diese Disc (30 Tage, per Disc-Fingerabdruck).

interface SuchKandidat {
  title: string
  year?: number
  poster?: string
  overview?: string
  type: string
  source: string
  id?: string
}

interface Props {
  devicePath: string
  vorschlag?: string
  isOpen: boolean
  onClose: () => void
  onUebernommen: () => void
}

export default function MetadataKorrektur({ devicePath, vorschlag, isOpen, onClose, onUebernommen }: Props) {
  const [suchbegriff, setSuchbegriff] = useState('')
  const [kandidaten, setKandidaten] = useState<SuchKandidat[]>([])
  const [laeuft, setLaeuft] = useState(false)
  const [fehler, setFehler] = useState<string | null>(null)
  const { theme } = useDarkMode()

  useEffect(() => {
    if (isOpen) {
      setSuchbegriff(vorschlag || '')
      setKandidaten([])
      setFehler(null)
    }
  }, [isOpen, vorschlag])

  const suchen = async () => {
    if (!suchbegriff) return
    setLaeuft(true)
    setFehler(null)
    try {
      const r = await api.get('/metadata/search', { params: { q: suchbegriff } })
      setKandidaten(r.data)
      if (r.data.length === 0) setFehler('Nichts gefunden — anderen Suchbegriff probieren.')
    } catch {
      setFehler('Suche fehlgeschlagen.')
    } finally {
      setLaeuft(false)
    }
  }

  const waehlen = async (k: SuchKandidat) => {
    try {
      await api.post('/metadata/override', {
        device_path: devicePath,
        title: k.title,
        year: k.year,
        poster: k.poster,
        overview: k.overview,
        type: k.type,
        source: k.source,
        id: k.id,
      })
      onUebernommen()
      onClose()
    } catch {
      setFehler('Übernehmen fehlgeschlagen.')
    }
  }

  if (!isOpen) return null

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
      <div className={`w-full max-w-2xl max-h-[85vh] flex flex-col rounded-xl shadow-2xl ${theme === 'dark' ? 'bg-slate-800' : 'bg-white'}`}>
        <div className={`px-6 py-4 border-b flex items-center justify-between ${theme === 'dark' ? 'border-slate-700' : 'border-slate-200'}`}>
          <div>
            <h2 className={`text-lg font-bold ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Richtigen Titel wählen</h2>
            <p className={`text-xs mt-0.5 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
              Deine Wahl gilt für diese Disc — auch beim nächsten Einlegen.
            </p>
          </div>
          <button onClick={onClose} className={`p-1.5 rounded ${theme === 'dark' ? 'hover:bg-slate-700 text-slate-400' : 'hover:bg-slate-100 text-slate-500'}`}>
            <X size={18} />
          </button>
        </div>

        <div className="p-6 overflow-y-auto">
          <div className="flex gap-3">
            <input
              value={suchbegriff}
              onChange={e => setSuchbegriff(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && suchen()}
              autoFocus
              placeholder="Titel eingeben…"
              className={`flex-1 px-4 py-2 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent ${theme === 'dark' ? 'bg-slate-700 border-slate-600 text-slate-100' : 'bg-white border-slate-300 text-slate-900'}`}
            />
            <button
              onClick={suchen}
              disabled={!suchbegriff || laeuft}
              className="flex items-center gap-2 px-5 py-2 rounded-lg bg-indigo-600 text-white hover:bg-indigo-700 transition-colors disabled:opacity-40"
            >
              {laeuft ? <Loader2 className="animate-spin" size={18} /> : <Search size={18} />}
              Suchen
            </button>
          </div>

          {fehler && <p className="text-sm text-rose-500 mt-3">{fehler}</p>}

          {kandidaten.length > 0 && (
            <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mt-4">
              {kandidaten.map((k, i) => (
                <button
                  key={i}
                  onClick={() => waehlen(k)}
                  className={`text-left rounded-lg border overflow-hidden transition-all hover:border-indigo-500 hover:shadow-lg ${theme === 'dark' ? 'bg-slate-900 border-slate-700' : 'bg-slate-50 border-slate-200'}`}
                >
                  {k.poster ? (
                    <img src={k.poster} alt={k.title} className="w-full h-40 object-cover" />
                  ) : (
                    <div className={`w-full h-40 flex items-center justify-center ${theme === 'dark' ? 'bg-slate-800 text-slate-600' : 'bg-slate-100 text-slate-400'}`}>
                      <Film size={32} />
                    </div>
                  )}
                  <div className="p-2">
                    <p className={`text-xs font-semibold leading-tight line-clamp-2 ${theme === 'dark' ? 'text-slate-200' : 'text-slate-800'}`}>{k.title}</p>
                    <p className={`text-xs mt-0.5 ${theme === 'dark' ? 'text-slate-500' : 'text-slate-400'}`}>
                      {k.year || '—'} · {k.type === 'tv' ? 'Serie' : 'Film'} · {k.source}
                    </p>
                  </div>
                </button>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  )
}
