import { useState, useEffect } from 'react'
import { Settings, Save, Disc, Cpu, Database, Globe, AlertCircle, CheckCircle } from 'lucide-react'
import { api } from '../lib/api'
import { useDarkMode } from '../context/ThemeContext'

interface SettingsState {
  tmdbApiKey: string
  tvdbApiKey: string
  outputDir: string
  movieDir: string
  seriesDir: string
  musicDir: string
  ripAllTracks: boolean
  mainFeatureOnly: boolean
  autoEject: boolean
  notificationWebhook: string
}

const defaultSettings: SettingsState = {
  tmdbApiKey: '',
  tvdbApiKey: '',
  outputDir: '/app/media',
  movieDir: 'movies',
  seriesDir: 'series',
  musicDir: 'music',
  ripAllTracks: true,
  mainFeatureOnly: false,
  autoEject: true,
  notificationWebhook: '',
}

export default function SettingsPage() {
  const [settings, setSettings] = useState<SettingsState>(defaultSettings)
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [saved, setSaved] = useState(false)
  const { theme } = useDarkMode()

  useEffect(() => {
    const loadSettings = async () => {
      try {
        const response = await api.get('/settings')
        // Leeres Objekt von der API = noch nichts gespeichert → Defaults behalten
        setSettings({ ...defaultSettings, ...response.data })
      } catch {
        setSettings(defaultSettings)
      } finally {
        setLoading(false)
      }
    }
    loadSettings()
  }, [])

  const handleChange = (field: keyof SettingsState, value: any) => {
    setSettings(prev => ({ ...prev, [field]: value }))
    setSaved(false)
  }

  const handleSave = async () => {
    setSaving(true)
    try {
      await api.post('/settings', settings)
      setSaved(true)
      setTimeout(() => setSaved(false), 3000)
    } finally {
      setSaving(false)
    }
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-[60vh]">
        <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-600"></div>
      </div>
    )
  }

  return (
    <div className={`max-w-4xl space-y-6 transition-colors duration-300 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
      <div className="flex flex-col gap-2 transition-colors duration-300">
        <h1 className={`text-3xl font-bold ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Einstellungen</h1>
        <p className={`text-sm ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Konfiguriere Rippy nach deinen Wünschen</p>
      </div>

      {saved && (
        <div className={`p-4 rounded-lg flex items-center gap-3 font-medium transition-colors duration-300 ${theme === 'dark' ? 'bg-emerald-900/30 border border-emerald-700 text-emerald-400' : 'bg-emerald-50 border border-emerald-200 text-emerald-700'}`}>
          <CheckCircle className="flex-shrink-0" size={24} />
          <span>Einstellungen erfolgreich gespeichert!</span>
        </div>
      )}

      <div className={`rounded-xl shadow-sm overflow-hidden transition-colors duration-300 ${theme === 'dark' ? 'bg-slate-800 border border-slate-700' : 'bg-white border border-slate-200'}`}>
        {/* Tabs */}
        <div className={`flex transition-colors duration-300 ${theme === 'dark' ? 'border-slate-700' : 'border-slate-200'} border-b`}>
          <TabButton icon={Disc} label="Ripping" isActive={true} darkMode={theme === 'dark'} />
          <TabButton icon={Cpu} label="Verarbeitung" isActive={false} darkMode={theme === 'dark'} />
          <TabButton icon={Database} label="Datenbank" isActive={false} darkMode={theme === 'dark'} />
          <TabButton icon={Globe} label="APIs" isActive={false} darkMode={theme === 'dark'} />
          <TabButton icon={AlertCircle} label="Benachrichtigungen" isActive={false} darkMode={theme === 'dark'} />
        </div>

        {/* Content */}
        <div className="p-6 space-y-8 transition-colors duration-300">
          {/* Ripping Settings */}
          <section>
            <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 transition-colors duration-300 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Disc size={20} className={theme === 'dark' ? 'text-indigo-400' : 'text-indigo-600'} />
              Ripping-Einstellungen
            </h2>
            
            <div className="space-y-4 transition-colors duration-300">
              <div className="flex items-center justify-between p-4 transition-colors duration-300">
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg transition-colors duration-300 ${theme === 'dark' ? 'bg-indigo-900/30 text-indigo-400' : 'bg-indigo-100 text-indigo-600'}`}>
                    <Disc size={20} />
                  </div>
                  <div>
                    <h3 className={`font-medium ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Alle Tracks rippen</h3>
                    <p className={`text-sm transition-colors duration-300 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Rippe alle Tracks einer CD (nicht nur Main Feature)</p>
                  </div>
                </div>
                <Toggle 
                  checked={settings.ripAllTracks} 
                  onChange={(v) => handleChange('ripAllTracks', v)} 
                  darkMode={theme === 'dark'}
                />
              </div>

              <div className={`flex items-center justify-between p-4 transition-colors duration-300 ${theme === 'dark' ? 'bg-slate-700/50 rounded-lg' : 'bg-slate-50 rounded-lg'}`}>
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg transition-colors duration-300 ${theme === 'dark' ? 'bg-purple-900/30 text-purple-400' : 'bg-purple-100 text-purple-600'}`}>
                    <Disc size={20} />
                  </div>
                  <div>
                    <h3 className={`font-medium ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Nur Hauptfeature</h3>
                    <p className={`text-sm transition-colors duration-300 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Rippe bei DVDs/Blu-rays nur das Hauptfeature</p>
                  </div>
                </div>
                <Toggle 
                  checked={settings.mainFeatureOnly} 
                  onChange={(v) => handleChange('mainFeatureOnly', v)} 
                  darkMode={theme === 'dark'}
                />
              </div>

              <div className={`flex items-center justify-between p-4 transition-colors duration-300 ${theme === 'dark' ? 'bg-slate-700/50 rounded-lg' : 'bg-slate-50 rounded-lg'}`}>
                <div className="flex items-center gap-3">
                  <div className={`p-2 rounded-lg transition-colors duration-300 ${theme === 'dark' ? 'bg-emerald-900/30 text-emerald-400' : 'bg-emerald-100 text-emerald-600'}`}>
                    <Disc size={20} />
                  </div>
                  <div>
                    <h3 className={`font-medium ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>Automatischer Auswurf</h3>
                    <p className={`text-sm transition-colors duration-300 ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Disk nach erfolgreichem Ripping auswerfen</p>
                  </div>
                </div>
                <Toggle 
                  checked={settings.autoEject} 
                  onChange={(v) => handleChange('autoEject', v)} 
                  darkMode={theme === 'dark'}
                />
              </div>
            </div>
          </section>

          {/* Output Directories */}
          <section>
            <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 transition-colors duration-300 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Database size={20} className={theme === 'dark' ? 'text-indigo-400' : 'text-indigo-600'} />
              Ausgabeverzeichnisse
            </h2>
            
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6 transition-colors duration-300">
              <div className="space-y-2 transition-colors duration-300">
                  <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                    Hauptverzeichnis
                  </label>
                  <input
                    type="text"
                    value={settings.outputDir}
                    onChange={(e) => handleChange('outputDir', e.target.value)}
                    className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200 focus:ring-indigo-500' : 'bg-white border-slate-300 text-slate-900 focus:ring-indigo-600'} border rounded-lg focus:ring-2 focus:border-transparent transition-all`}
                    placeholder="/app/media"
                  />
                  <p className={`text-xs ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>Basisverzeichnis für alle Ausgaben</p>
              </div>

              <div className="space-y-2 transition-colors duration-300">
                <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  Filme
                </label>
                <input
                  type="text"
                  value={settings.movieDir}
                  onChange={(e) => handleChange('movieDir', e.target.value)}
                  className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                  placeholder="movies"
                />
              </div>

              <div className="space-y-2 transition-colors duration-300">
                <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  Serien
                </label>
                <input
                  type="text"
                  value={settings.seriesDir}
                  onChange={(e) => handleChange('seriesDir', e.target.value)}
                  className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                  placeholder="series"
                />
              </div>

              <div className="space-y-2 transition-colors duration-300">
                <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  Musik
                </label>
                <input
                  type="text"
                  value={settings.musicDir}
                  onChange={(e) => handleChange('musicDir', e.target.value)}
                  className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                  placeholder="music"
                />
              </div>
            </div>
          </section>

          {/* API Keys */}
          <section>
            <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 transition-colors duration-300 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <Globe size={20} className={theme === 'dark' ? 'text-indigo-400' : 'text-indigo-600'} />
              API-Schlüssel
            </h2>
            
            <div className="space-y-4 transition-colors duration-300">
              <div className="space-y-2 transition-colors duration-300">
                <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  TMDB API Key
                </label>
                <input
                  type="password"
                  value={settings.tmdbApiKey}
                  onChange={(e) => handleChange('tmdbApiKey', e.target.value)}
                  className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                  placeholder="Dein TMDB API Key"
                />
                <p className={`text-xs ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
                  Hol dir einen Key auf <a href="https://www.themoviedb.org/" target="_blank" rel="noopener noreferrer" className={`${theme === 'dark' ? 'text-indigo-400 hover:underline' : 'text-indigo-600 hover:underline'}`}>themoviedb.org</a>
                </p>
              </div>

              <div className="space-y-2 transition-colors duration-300">
                <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                  TVDb API Key
                </label>
                <input
                  type="password"
                  value={settings.tvdbApiKey}
                  onChange={(e) => handleChange('tvdbApiKey', e.target.value)}
                  className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                  placeholder="Dein TVDb API Key"
                />
              </div>
            </div>
          </section>

          {/* Webhook */}
          <section>
            <h2 className={`text-lg font-semibold mb-4 flex items-center gap-2 transition-colors duration-300 ${theme === 'dark' ? 'text-slate-100' : 'text-slate-900'}`}>
              <AlertCircle size={20} className={theme === 'dark' ? 'text-indigo-400' : 'text-indigo-600'} />
              Webhook-Benachrichtigungen
            </h2>
            
            <div className="space-y-2 transition-colors duration-300">
              <label className={`block text-sm font-medium ${theme === 'dark' ? 'text-slate-300' : 'text-slate-700'}`}>
                Webhook URL
              </label>
              <input
                type="text"
                value={settings.notificationWebhook}
                onChange={(e) => handleChange('notificationWebhook', e.target.value)}
                className={`w-full px-3 py-2 ${theme === 'dark' ? 'bg-slate-800 border-slate-600 text-slate-200' : 'bg-white border-slate-300 text-slate-900'} border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent transition-all`}
                placeholder="https://discord.com/api/webhooks/..."
              />
              <p className={`text-xs ${theme === 'dark' ? 'text-slate-400' : 'text-slate-500'}`}>
                Optional: URL für Benachrichtigungen bei Job-Ende (Discord, Slack, etc.)
              </p>
            </div>
          </section>

          {/* Save Button */}
          <div className={`flex items-center justify-end gap-4 pt-6 transition-colors duration-300 ${theme === 'dark' ? 'border-slate-700' : 'border-slate-200'} border-t`}>
            <button
              onClick={handleSave}
              disabled={saving}
              className="flex items-center gap-2 px-6 py-2.5 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"></div>
                  Speichern...
                </>
              ) : (
                <>
                  <Save size={20} />
                  Einstellungen speichern
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

function TabButton({ icon: Icon, label, isActive, darkMode }: { icon: any, label: string, isActive: boolean, darkMode: boolean }) {
  const { theme } = useDarkMode()
  return (
    <button
      className={`px-6 py-3 text-sm font-medium transition-colors border-b-2 ${
        isActive
          ? `${darkMode ? 'border-indigo-500 text-indigo-400' : 'border-indigo-600 text-indigo-600'}`
          : `${darkMode ? 'border-transparent text-slate-400 hover:text-slate-300' : 'border-transparent text-slate-500 hover:text-slate-700'}`
      }`}
    >
      {label}
    </button>
  )
}

function Toggle({ checked, onChange, darkMode }: { checked: boolean, onChange: (v: boolean) => void, darkMode: boolean }) {
  const { theme } = useDarkMode()
  return (
    <button
      onClick={() => onChange(!checked)}
      className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${
        checked ? 'bg-indigo-600' : darkMode ? 'bg-slate-600' : 'bg-slate-300'
      }`}
    >
      <span
        className={`${
          checked ? 'translate-x-6' : 'translate-x-1'
        } inline-block h-4 w-4 transform rounded-full bg-white transition-transform`}
      />
    </button>
  )
}
